Yeqela kokuqukethwe okuyinhloko Yeqela ku-docs navigation
Check
in English

I-JavaScript

Yenza i-Bootstrap iphile ngama-plugin wethu we-JavaScript ongawakhetha. Funda mayelana ne-plugin ngayinye, idatha yethu nezinketho zohlelo lwe-API, nokuningi.

Ngamunye noma ihlanganiswe

Ama-plugin angafakwa ngawodwana (usebenzisa i-Bootstrap's individual js/dist/*.js), noma wonke ngesikhathi esisodwa usebenzisa bootstrap.jsnoma i-minified bootstrap.min.js(ungafaki kokubili).

Uma usebenzisa i-bundler (Webpack, Parcel, Vite…), ungasebenzisa /js/dist/*.jsamafayela aselungile nge-UMD.

Ukusetshenziswa nezinhlaka ze-JavaScript

Nakuba i-Bootstrap CSS ingasetshenziswa nanoma yiluphi uhlaka, i-Bootstrap JavaScript ayihambelani ngokugcwele nezinhlaka ze-JavaScript ezifana ne-React, Vue, ne-Angular ethatha ulwazi olugcwele lwe-DOM. Kokubili i-Bootstrap kanye nohlaka kungase kuzame ukuguqula isici se-DOM esifanayo, kubangele iziphazamisi ezifana nokwehliswayo okubambeke endaweni “evulekile”.

Enye indlela engcono yalabo abasebenzisa lolu hlobo lwezinhlaka ukusebenzisa iphakheji eqondene nohlaka esikhundleni se -Bootstrap JavaScript. Nazi ezinye zezinketho ezidume kakhulu:

Ukusebenzisa i-Bootstrap njengemojula

Zizame wena! Landa ikhodi yomthombo kanye nedemo yokusebenza ukuze usebenzise i-Bootstrap njengemojula ye-ES kusuka kukhosombe ye- twbs/izibonelo . Ungakwazi futhi ukuvula isibonelo kokuthi StackBlitz .

Sinikeza inguqulo ye-Bootstrap eyakhelwe njenge- ESM( bootstrap.esm.jskanye bootstrap.esm.min.js) ekuvumela ukuthi usebenzise i-Bootstrap njengemojula esipheqululini, uma iziphequluli zakho eziqondiwe ziyisekela .

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

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

Uma kuqhathaniswa nezinqwaba ze-JS, ukusebenzisa i-ESM esipheqululini kudinga ukuthi usebenzise indlela ephelele negama lefayela esikhundleni segama lemojuli. Funda kabanzi mayelana namamojula e-JS esipheqululini. Yingakho sisebenzisa 'bootstrap.esm.min.js'esikhundleni 'bootstrap'saphezulu. Kodwa-ke, lokhu kuphinde kube nzima ukuncika kwethu kwe-Popper, engenisa i-Popper ku-JavaScript yethu kanje:

import * as Popper from "@popperjs/core"

Uma uzama lokhu njengoba kunjalo, uzobona iphutha kukhonsoli njengokulandelayo:

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

Ukuze ulungise lokhu, ungasebenzisa i- importmapukuze uxazulule amagama emojula angafanele ukuze uqedele izindlela. Uma iziphequluli zakho eziqondisiwe zingakusekeli , importmapuzodinga ukusebenzisa iphrojekthi ye- es-module-shims . Nansi indlela esebenza ngayo ku-Bootstrap ne-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>

Ukuncika

Amanye ama-plugin nezingxenye ze-CSS zincike kwamanye ama-plugin. Uma ufaka ama-plugin ngawodwana, qiniseka ukuthi uhlola lokhu kuncika kumadokhumenti.

Okwehliswayo kwethu, ama-popover, namathiphu wamathuluzi nakho kuncike ku- Popper .

Izibaluli zedatha

Cishe wonke ama-plugin e-Bootstrap angavulwa futhi amiswe nge-HTML iyodwa ngezibaluli zedatha (indlela yethu esiyikhethayo yokusebenzisa ukusebenza kwe-JavaScript). Qiniseka ukuthi usebenzisa isethi eyodwa yezibaluli zedatha entweni eyodwa (isb, awukwazi ukucupha ithiphu yamathuluzi nemodali enkinobho efanayo.)

Njengoba izinketho zingadluliswa ngezibaluli zedatha noma i-JavaScript, ungakwazi ukwengeza igama lenketho kokuthi data-bs-, njengaku data-bs-animation="{value}". Qiniseka ukuthi ushintsha uhlobo lwekesi legama lenketho lisuka ku- “ camelCase ” liye ku- “ kebab-case ” lapho udlulisa izinketho ngezibaluli zedatha. Isibonelo, sebenzisa data-bs-custom-class="beautifier"esikhundleni se- data-bs-customClass="beautifier".

Kusukela ku-Bootstrap 5.2.0, zonke izingxenye zisekela isibaluli sedatha egodliwe esihlolwayodata-bs-config esingafaka ukucushwa kwengxenye elula njengochungechunge lwe-JSON. Uma into inezibaluli , inani lokugcina lizoba data-bs-config='{"delay":0, "title":123}'futhi izibaluli zedatha ezihlukene zizokhipha amanani anikezwe ngomhla ka- . Ngaphezu kwalokho, izibaluli zedatha ezikhona ziyakwazi ukubeka amanani e-JSON afana .data-bs-title="456"title456data-bs-configdata-bs-delay='{"show":0,"hide":150}'

Abakhethi

Sisebenzisa okomdabu querySelectorkanye querySelectorAllnezindlela ukubuza ngezinto ze-DOM ngezizathu zokusebenza, ngakho-ke kufanele usebenzise izikhethi ezivumelekile . Uma usebenzisa izikhethi ezikhethekile ezifana ne- collapse:Example, qiniseka ukuthi uyazibalekela.

Imicimbi

I-Bootstrap inikeza imicimbi yangokwezifiso yezenzo ezihlukile zama-plugin. Ngokuvamile, lezi ziza ngendlela engapheli kanye nenkathi edlule - lapho okungapheli (isb. show) kuqalwa ekuqaleni komcimbi, futhi isimo saso sokuhlanganyela esidlule (isib. shown) siqaliswa lapho kuqedwa isenzo.

Yonke imicimbi engapheli inikeza preventDefault()ukusebenza. Lokhu kunikeza ikhono lokumisa ukwenziwa kwesenzo ngaphambi kokuthi siqale. Ukubuyisela amanga kusiphathi somcimbi nakho kuzoshaya ngokuzenzakalelayo preventDefault().

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

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

I-Programmatic API

Bonke abakhi bamukela into oyikhethayo noma lutho (okuqala i-plugin ngokuziphatha kwayo okuzenzakalelayo):

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

Uma ungathanda ukuthola isibonelo esithile se-plugin, i-plugin ngayinye iveza getInstanceindlela. Isibonelo, ukubuyisa isenzakalo ngokuqondile ku-elementi:

bootstrap.Popover.getInstance(myPopoverEl)

Le ndlela izobuya nulluma isenzakalo singaqaliswa phezu kwento eceliwe.

Kungenjalo, getOrCreateInstanceingasetshenziswa ukuthola isenzakalo esihlotshaniswa nento ye-DOM, noma udale entsha uma kwenzeka ingaqaliswanga.

bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)

Esimeni lapho isenzakalo singazange siqaliswe, singase samukele futhi sisebenzise into yokuzikhethela yokucushwa njengempikiswano yesibili.

Izikhethi ze-CSS kubakhi

Ngokungeziwe kokuthi getInstancenezindlela getOrCreateInstance, bonke abakhi be-plugin bangamukela isici se-DOM noma isikhethi esivumelekile se- CSS njengengxabano yokuqala. Izakhi ze-plugin zitholakala querySelectorngendlela njengoba ama-plugin ethu esekela into eyodwa kuphela.

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')

Imisebenzi ye-Asynchronous kanye noshintsho

Zonke izindlela ze-API zohlelo azivumelanisi futhi zibuyela kofonayo uma uguquko seluqalile, kodwa ngaphambi kokuthi luphele . Ukuze wenze isenzo uma inguquko isiqedile, ungalalela umcimbi ohambisanayo.

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

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

Ngokungeziwe, ikholi yendlela engxenyeni yoshintsho izozitshwa .

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 !!

disposeindlela

Nakuba kungase kubonakale kulungile ukusebenzisa disposeindlela ngokushesha ngemva hide(), kuzoholela emiphumeleni engalungile. Nasi isibonelo sokusebenzisa inkinga:

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

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

Izilungiselelo ezizenzakalelayo

Ungashintsha izilungiselelo ezizenzakalelayo ze-plugin ngokulungisa Constructor.Defaultinto ye-plugin:

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

Izindlela nezakhiwo

Yonke i-plugin ye-Bootstrap iveza izindlela ezilandelayo kanye nezakhiwo ezimile.

Indlela Incazelo
dispose Icekela phansi i-modal yento ethile. (Isusa idatha egciniwe kusici se-DOM)
getInstance Indlela emile ekuvumela ukuthi uthole isibonelo se-modal esihlotshaniswa nento ye-DOM.
getOrCreateInstance Indlela emile ekuvumela ukuthi uthole imodeli ye-modal ehlotshaniswa nento ye-DOM, noma udale entsha uma kwenzeka ingaqaliswanga.
Impahla engashintshi Incazelo
NAME Ibuyisela igama le-plugin. (Isibonelo bootstrap.Tooltip.NAME:)
VERSION Inguqulo ye-plugin ngayinye ye-Bootstrap ingafinyelelwa ngesakhiwo somakhi VERSIONwe-plugin (Isibonelo bootstrap.Tooltip.VERSION:)

I-Sanitizer

Amathuluzi nama-Popovers asebenzisa isicoci esakhelwe ngaphakathi ukuze sihlanze izinketho ezamukela i-HTML.

Inani elizenzakalelayo allowListlilandelayo:

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: []
}

Uma ufuna ukwengeza amanani amasha kulokhu okumisiwe allowListungenza okulandelayo:

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)

Uma ufuna ukweqa isibulali magciwane sethu ngoba ukhetha ukusebenzisa umtapo wolwazi ozinikele, isibonelo DOMPurify , kufanele wenze okulandelayo:

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

Ngokuzithandela usebenzisa i-jQuery

Awuyidingi i-jQuery ku-Bootstrap 5 , kodwa kusengenzeka ukusebenzisa izingxenye zethu nge-jQuery. Uma i-Bootstrap ithola jQueryentweni window, izongeza zonke izingxenye zethu kusistimu ye-plugin ye-jQuery. Lokhu kukuvumela ukuthi wenze okulandelayo:

$('[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

Okufanayo kuya kwezinye izingxenye zethu.

Akukho ukungqubuzana

Kwesinye isikhathi kuyadingeka ukusebenzisa ama-plugin e-Bootstrap nezinye izinhlaka ze-UI. Kulezi zimo, ukungqubuzana kwendawo yamagama kungenzeka ngezikhathi ezithile. Uma lokhu kwenzeka, ungashayela .noConflicti-plugin ofisa ukubuyisela inani layo.

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

I-Bootstrap ayisekeli ngokusemthethweni amalabhulali e-JavaScript ezinkampani zangaphandle njenge-Prototype noma i-jQuery UI. Ngaphandle .noConflictkwemicimbi enezikhala zamagama, kungase kube nezinkinga zokusebenzisana okudingeka uzilungise uwedwa.

Imicimbi ye-jQuery

I- Bootstrap izobona i-jQuery uma jQueryikhona windowentweni futhi asikho data-bs-no-jqueryisibaluli esisethiwe <body>. Uma i-jQuery itholakala, i-Bootstrap izokhipha imicimbi ngenxa yesistimu yomcimbi ye-jQuery. Ngakho-ke uma ufuna ukulalela imicimbi ye-Bootstrap, kuzodingeka usebenzise izindlela ze-jQuery ( .on, .one) esikhundleni sokuthi addEventListener.

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

I-JavaScript ivaliwe

Ama-plugin e-Bootstrap awanakho ukubuyela emuva okukhethekile uma i-JavaScript ivaliwe. Uma unendaba nolwazi lomsebenzisi kulesi simo, sebenzisa <noscript>ukuchaza isimo (nokuthi ungayenza kanjani i-JavaScript isebenze kabusha) kubasebenzisi bakho, kanye/noma wengeze okwakho okubuyela emuva ngokwezifiso.