Tlolela go diteng tše kgolo Tlolela go docs navigation
Check
in English

JavaScript

Tliša Bootstrap bophelong ka di-plugin tša rena tša JavaScript tša boikhethelo. Ithute ka plugin e nngwe le e nngwe, dikgetho tša rena tša data le tša lenaneo la API, le tše dingwe.

Motho ka o tee ka o tee goba e kgobokeditšwego

Di-plugin di ka akaretšwa ka botee (go diriša Bootstrap’s individual js/dist/*.js), goba ka moka ka nako e tee di diriša bootstrap.jsgoba tšeo di fokoditšwego bootstrap.min.js(o se ke wa akaretša ka bobedi).

Ge o šomiša bundler (Webpack, Parcel, Vite...), o ka šomiša /js/dist/*.jsdifaele tšeo di lokilego UMD.

Tšhomišo ka ditlhako tša JavaScript

Le ge Bootstrap CSS e ka šomišwa le tlhako efe goba efe, JavaScript ya Bootstrap ga e sepelelane ka botlalo le ditlhako tša JavaScript tša go swana le React, Vue, le Angular tšeo di tšeago tsebo ka botlalo ya DOM. Bobedi Bootstrap le tlhako di ka leka go fetoša elemente e swanago ya DOM, go feleletša ka diphošo tša go swana le di-dropdown tšeo di kgomaretšego boemong bja “bulegilego”.

Selo se sengwe se sekaone go bao ba šomišago mohuta wo wa ditlhako ke go šomiša sephuthelwana se se itšego sa tlhako go e na le JavaScript ya Bootstrap. Tše dingwe tša dikgetho tše di tumilego kudu ke tše:

Go diriša Bootstrap bjalo ka modula

E leke ka bowena! Download khoutu ya mohlodi le demo e sebetsang bakeng sa ho sebelisa Bootstrap e le modula wa ES ho tloha polokelo ya twbs / mehlala . O ka bula gape mohlala go StackBlitz .

Re fana ka phetolelo ya Bootstrap e agilwego bjalo ka ESM( bootstrap.esm.jsle bootstrap.esm.min.js) yeo e go dumelelago go šomiša Bootstrap bjalo ka modula ka go sephephediši, ge e le gore diphensele tša gago tšeo di nepišitšwego di e thekga .

<script type="module">
  import { Toast } from 'bootstrap.esm.min.js'

  Array.from(document.querySelectorAll('.toast'))
    .forEach(toastNode => new Toast(toastNode))
</script>

Ge go bapetšwa le diphuthelwana tša JS, go šomiša ESM ka go sephephediši go nyaka gore o šomiše tsela ye e tletšego le leina la faele go e na le leina la modula. Bala go feta fa ka dimmojule JS ka sebadi. Ke ka fao re šomišago 'bootstrap.esm.min.js'go e na le ka 'bootstrap'godimo. Le ge go le bjalo, se se raragantšhwa gape ke go ithekga ga rena ka Popper, mo go tsenyago Popper ka gare ga JavaScript ya rena ka tsela yeo:

import * as Popper from "@popperjs/core"

Ge o leka se bjalo ka ge se le bjalo, o tla bona phošo ka gare ga khonsule go swana le ye e latelago:

Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".

Go lokiša se, o ka šomiša an importmapgo rarolla maina a dimmojule tša boithatelo go phetha ditsela. Ge e ba diphensele tša gago tšeo di nepišitšwego di sa thekge importmap, o tla swanelwa ke go diriša projeke ya es-module-shims . Ke kamoo e šomago ka gona bakeng sa Bootstrap le Popper:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
    <title>Hello, modularity!</title>
  </head>
  <body>
    <h1>Hello, modularity!</h1>
    <button id="popoverButton" type="button" class="btn btn-primary btn-lg" class="btn btn-lg btn-danger" data-bs-toggle="popover" title="ESM in Browser" data-bs-content="Bang!">Custom popover</button>

    <script async src="https://cdn.jsdelivr.net/npm/es-module-shims@1/dist/es-module-shims.min.js" crossorigin="anonymous"></script>
    <script type="importmap">
    {
      "imports": {
        "@popperjs/core": "https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js",
        "bootstrap": "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.esm.min.js"
      }
    }
    </script>
    <script type="module">
      import * as bootstrap from 'bootstrap'

      new bootstrap.Popover(document.getElementById('popoverButton'))
    </script>
  </body>
</html>

Ditshepetšo tša go ithekga

Di-plugin tše dingwe le dikarolo tša CSS di ithekgile ka di-plugin tše dingwe. Ge o akaretša di-plugin ka botee, kgonthiša gore o hlahloba dilo tše tšeo di ithekgilego ka tšona ka go di-doc.

Di-dropdown tša rena, di-popover le di- tooltis le tšona di ithekgile ka Popper .

Dika tša datha

Mo e nyakilego go ba di-plugin ka moka tša Bootstrap di ka kgontšhwa le go beakanywa ka HTML e nnoši ka dika tša data (tsela ya rena yeo re e ratago ya go diriša mošomo wa JavaScript). Kgonthiša gore o šomiša fela sete e tee ya dika tša datha go elemente e tee (mohlala, o ka se kgone go hlohleletša keletšo ya sedirišwa le modal go tšwa go konope ye e swanago.)

Bjalo ka ge dikgetho di ka fetišwa ka dika tša datha goba JavaScript, o ka tlaleletša leina la kgetho go data-bs-, bjalo ka go data-bs-animation="{value}". Kgonthiša gore o fetoša mohuta wa molato wa leina la kgetho go tšwa go “ camelCase ” go ya go “ kebab-case ” ge o fetiša dikgetho ka dika tša datha. Ka mohlala, diriša data-bs-custom-class="beautifier"go e na le data-bs-customClass="beautifier".

Go tloga go Bootstrap 5.2.0, dikarolo ka moka di thekga seka sa datha ye e bolokilwego ya tekodata-bs-config yeo e ka beago peakanyo ya karolo ye bonolo bjalo ka thapo ya JSON. Ge elemente e na data-bs-config='{"delay":0, "title":123}'le le data-bs-title="456"dika, boleng bja mafelelo titlee tla ba 456gomme dika tša datha tše di aroganego di tla phaela ka thoko boleng bjo bo filwego go data-bs-config. Go tlaleletša, dika tša datha tše di lego gona di kgona go bea dikelo tša JSON go swana le data-bs-delay='{"show":0,"hide":150}'.

Bakgethi ba

Re šomiša setlogo querySelectorle querySelectorAllmekgwa go botšiša dielemente tša DOM ka mabaka a tshepedišo, ka fao o swanetše go šomiša dikgetho tše di šomago . Ge e ba o diriša dikgetho tše di kgethegilego tša go swana le collapse:Example, kgonthišetša gore o di tšhaba.

Ditiragalo

Bootstrap e fana ka ditiragalo tša tlwaelo bakeng sa bontši bja ditiro tše di kgethegilego tša di-plugin. Ka kakaretšo, tše di tla ka mokgwa wa go se fele le wa lediri la nakong ye e fetilego - moo lediri la go se fele (ex. show) le hlohleletšwago mathomong a tiragalo, gomme sebopego sa lona sa lediri la nakong ye e fetilego (ex. shown) se hlohleletšwa ge tiro e phethilwe.

Ditiragalo ka moka tša go se fele di fa preventDefault()mošomo. Se se fa bokgoni bja go emiša phethagatšo ya tiro pele e thoma. Go bušetša maaka go tšwa go modiriši wa tiragalo le gona go tla bitša ka go iketla preventDefault().

const myModal = document.querySelector('#myModal')

myModal.addEventListener('show.bs.modal', event => {
  if (!data) {
    return event.preventDefault() // stops modal from being shown
  }
})

API ya lenaneo

Baagi ka moka ba amogela selo sa dikgetho tša boikhethelo goba ga go selo (seo se thomago plugin ka boitshwaro bja yona bja go se fetoge):

const myModalEl = document.querySelector('#myModal')

const modal = new bootstrap.Modal(myModalEl) // initialized with defaults

const configObject = { keyboard: false }
const modal1 = new bootstrap.Modal(myModalEl, configObject) // initialized with no keyboard

Ge o rata go hwetša mohlala wo o itšego wa plugin, plugin ye nngwe le ye nngwe e pepentšha getInstancemokgwa. Go fa mohlala, go hwetša mohlala thwii go tšwa go elemente:

bootstrap.Popover.getInstance(myPopoverEl)

Mokgwa wo o tla boa nullge e le gore mohlala ga se wa thongwa godimo ga elemente ye e kgopetšwego.

Ka go fapana le moo, getOrCreateInstancee ka šomišwa go hwetša mohlala wo o amanago le elemente ya DOM, goba go hlama ye mpsha ge go ka direga gore e be e sa thongwa.

bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)

Ge go ka direga gore mohlala o se wa thongwa, o ka amogela le go šomiša selo sa peakanyo ya boikgethelo bjalo ka ngangišano ya bobedi.

Bakgethi ba CSS ka gare ga baagi

Go tlaleletša go mekgwa ya getInstancele getOrCreateInstance, baagi ka moka ba plugin ba ka amogela elemente ya DOM goba mokgethi wa CSS wo o šomago bjalo ka ngangišano ya mathomo. Dielemente tša di-plugin di hwetšwa ka querySelectormokgwa ka ge di-plugin tša rena di thekga feela elemente e tee.

const modal = new bootstrap.Modal('#myModal')
const dropdown = new bootstrap.Dropdown('[data-bs-toggle="dropdown"]')
const offcanvas = bootstrap.Offcanvas.getInstance('#myOffcanvas')
const alert = bootstrap.Alert.getOrCreateInstance('#myAlert')

Mešomo ya asynchronous le diphetogo

Mekgwa ka moka ya lenaneo la API ga e na asynchronous gomme e boela go mogala ge phetogo e thomile, eupša pele e fela . Gore o kgone go phethagatša tiro ge phetogo e fedile, o ka theeletša tiragalo ye e swanetšego.

const myCollapseEl = document.querySelector('#myCollapse')

myCollapseEl.addEventListener('shown.bs.collapse', event => {
  // Action to execute once the collapsible area is expanded
})

Go tlaleletša, pitšo ya mokgwa go karolo ya phetogo e tla hlokomologwa .

const myCarouselEl = document.querySelector('#myCarousel')
const carousel = bootstrap.Carousel.getInstance(myCarouselEl) // Retrieve a Carousel instance

myCarouselEl.addEventListener('slid.bs.carousel', event => {
  carousel.to('2') // Will slide to the slide 2 as soon as the transition to slide 1 is finished
})

carousel.to('1') // Will start sliding to the slide 1 and returns to the caller
carousel.to('2') // !! Will be ignored, as the transition to the slide 1 is not finished !!

disposemokgwa

Le ge go ka bonagala go nepagetše go diriša disposemokgwa gatee-tee ka morago ga hide(), go tla lebiša dipoelong tše di fošagetšego. Mohlala wa tšhomišo ya bothata ke wo:

const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous

myModal.addEventListener('shown.bs.hidden', event => {
  myModal.dispose()
})

Dipeakanyo tša go se fetoge

O ka fetola dipeakanyo tša go se fetoge tša plugin ka go fetoša Constructor.Defaultselo sa plugin:

// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false

Mekgwa le thepa

Plugin ye nngwe le ye nngwe ya Bootstrap e pepentšha mekgwa ye e latelago le dithoto tša go se fetoge.

Mokgwa Tlhalošo
dispose E senya modal ya elemente. (E tloša ya data ye e bolokilwego go elemente ya DOM)
getInstance Mokgwa wa go se fetoge wo o go dumelelago go hwetša mohlala wa modal wo o amanago le elemente ya DOM.
getOrCreateInstance Mokgwa wa go se fetoge wo o go dumelelago go hwetša mohlala wa modal wo o amanago le elemente ya DOM, goba go hlama ye mpsha ge go ka direga gore e be e sa thongwa.
Thepa e sa fetoheng Tlhalošo
NAME E bušetša leina la plugin. (Mohlala: bootstrap.Tooltip.NAME) .
VERSION Phetolelo ya e nngwe le e nngwe ya di-plugin tša Bootstrap e ka fihlelelwa ka VERSIONthepa ya moagi wa plugin (Mohlala: bootstrap.Tooltip.VERSION) .

Sedirišwa sa go hlwekiša

Tooltips le Popovers sebelisa rona a haha-ka sanitizer ho sanitize dikgetho tse amohelang HTML.

Boleng bja go se fetoge allowListke bjo bo latelago:

const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i
const DefaultAllowlist = {
  // Global attributes allowed on any supplied element below.
  '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN],
  a: ['target', 'href', 'title', 'rel'],
  area: [],
  b: [],
  br: [],
  col: [],
  code: [],
  div: [],
  em: [],
  hr: [],
  h1: [],
  h2: [],
  h3: [],
  h4: [],
  h5: [],
  h6: [],
  i: [],
  img: ['src', 'srcset', 'alt', 'title', 'width', 'height'],
  li: [],
  ol: [],
  p: [],
  pre: [],
  s: [],
  small: [],
  span: [],
  sub: [],
  sup: [],
  strong: [],
  u: [],
  ul: []
}

Ge o nyaka go oketša dikelo tše mpsha go tlwaelo ye allowListo ka dira tše di latelago:

const myDefaultAllowList = bootstrap.Tooltip.Default.allowList

// To allow table elements
myDefaultAllowList.table = []

// To allow td elements and data-bs-option attributes on td elements
myDefaultAllowList.td = ['data-bs-option']

// You can push your custom regex to validate your attributes.
// Be careful about your regular expressions being too lax
const myCustomRegex = /^data-my-app-[\w-]+/
myDefaultAllowList['*'].push(myCustomRegex)

Ge e ba o nyaka go tlola sanitizer ya rena ka gobane o rata go diriša bokgobapuku bjo bo kgethegilego, mohlala DOMPurify , o swanetše go dira tše di latelago:

const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
  sanitizeFn(content) {
    return DOMPurify.sanitize(content)
  }
})

Ka boikgethelo sebelisa jQuery

Ga o hloke jQuery go Bootstrap 5 , eupša go sa dutše go kgonega go diriša dikarolo tša rena ka jQuery. Ge e ba Bootstrap e lemoga jQueryka gare ga windowselo, e tla oketša dikarolo tša rena ka moka ka tshepedišong ya plugin ya jQuery. Se se go dumelela go dira tše di latelago:

$('[data-bs-toggle="tooltip"]').tooltip() // to enable tooltips, with default configuration

$('[data-bs-toggle="tooltip"]').tooltip({ boundary: 'clippingParents', customClass: 'myClass' }) // to initialize tooltips with given configuration

$('#myTooltip').tooltip('show') // to trigger `show` method

Go bjalo le ka dikarolo tša rena tše dingwe.

Ga go na thulano

Ka dinako tše dingwe go a nyakega go diriša di-plugin tša Bootstrap le ditlhako tše dingwe tša UI. Maemong a, dithulano tša sekgoba sa maina di ka direga ka dinako tše dingwe. Ge se se direga, o ka bitša .noConflictplugin yeo o nyakago go bušetša boleng bja yona.

const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality

Bootstrap ga e thekge semmušo dilaeborari tša JavaScript tša mokgatlo wa boraro go swana le Prototype goba jQuery UI. Go sa šetšwe .noConflictle ditiragalo tša sekgoba sa maina, go ka ba le mathata a go sepelelana ao o swanetšego go a lokiša ka bowena.

jDitiragalo tša potšišo

Bootstrap e tla lemoga jQuery ge e le gore jQuerye gona ka gare ga windowselo gomme ga go na data-bs-no-jqueryseka seo se beilwego go <body>. Ge e ba jQuery e hwetšwa, Bootstrap e tla ntšha ditiragalo ka lebaka la tshepedišo ya ditiragalo ya jQuery. Ka fao ge o nyaka go theeletša ditiragalo tša Bootstrap, o tla swanelwa ke go šomiša mekgwa ya jQuery ( .on, .one) go e na le addEventListener.

$('#myTab a').on('shown.bs.tab', () => {
  // do something...
})

JavaScript e šitišitšwe

Di-plugin tša Bootstrap ga di na fallback e kgethegilego ge JavaScript e šitišitšwe. Ge e le gore o na le taba le maitemogelo a modiriši tabeng ye, šomiša <noscript>go hlaloša seemo (le ka moo o ka kgontšhago JavaScript gape) go badiriši ba gago, le/goba go oketša di-fallback tša gago tša tlwaelo.