Salá koleka na makambo ya ntina Salta na navigation ya docs
in English

JavaScript ya kosala

Mema Bootstrap na bomoi na ba plugins na biso ya JavaScript oyo okoki kopona. Yekola na ntina ya plugin moko na moko, ba données na biso mpe ba options ya API programmatique, mpe mingi mosusu.

Moto na moto to oyo esangisi yango

Ba plugins ekoki kozala na kati moko moko (kosalela Bootstrap's individual js/dist/*.js), to nyonso na mbala moko kosalela bootstrap.jsto oyo ekitisami bootstrap.min.js(kokɔtisa nyonso mibale te).

Soki osaleli bundler (Webpack, Rollup...), okoki kosalela /js/dist/*.jsba fichiers oyo ezali prêt ya UMD.

Kosalela Bootstrap lokola module

Tozali kopesa version ya Bootstrap oyo etongami lokola ESM( bootstrap.esm.jsmpe bootstrap.esm.min.js) oyo epesaka yo nzela ya kosalela Bootstrap lokola module na navigateur na yo, soki ba navigateurs na yo oyo ozali koluka ezali kosunga yango .

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

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

Ba plugins oyo ekokani te

Na tina ya ba limitations ya navigateur, ba plugins na biso misusu, elingi koloba ba plugins ya Dropdown, Tooltip na Popover, ekoki kosalelama te na <script>balise oyo ezali na moduletype po e dépend na Popper. Mpo na koyeba makambo mingi na ntina na likambo yango tala awa .

Ba dépendances

Ba plugins misusu na ba composants ya CSS etali ba plugins misusu. Soki otie ba plugins moko moko, sala makasi otala ba dépendances oyo na ba docs.

Ba dropdowns na biso, ba popovers na ba totipps na biso pe etali Popper .

Olingi naino kosalela jQuery? Ekoki kosalema!

Bootstrap 5 esalemi mpo na kosalelama kozanga jQuery, kasi ezali kaka na nzela ya kosalela ba composants na biso na jQuery. Soki Bootstrap e détecté jQueryna windowobjet ekobakisa ba composants na biso nionso na système ya plugin ya jQuery; yango elingi koloba ete okozala na makoki ya kosala $('[data-bs-toggle="tooltip"]').tooltip()mpo na kofungola ba toli ya bisaleli. Ezali mpe bongo mpo na biloko na biso mosusu.

Ba attributs ya ba données

Pene na ba plugins nionso ya Bootstrap ekoki kozala activé mpe configuré na nzela ya HTML kaka na ba attributs ya ba données (lolenge na biso ya kosalela fonctionnalité ya JavaScript oyo tolingaka mingi). Sala makasi ya kosalela kaka ensemble moko ya ba attributs ya ba données na élément moko (ndakisa, okoki te ko déclencher tooltip mpe modal na bouton moko.)

Bato oyo baponaka

Actuellement pona ko requêter ba éléments DOM tosalelaka ba méthodes natives querySelectorpe querySelectorAllpona ba raisons ya performance, donc il faut osalela ba sélecteurs valides . Soki osaleli ba sélecteurs spéciaux, na ndakisa: collapse:Examplesala makasi okima yango.

Makambo oyo esalemaki

Bootstrap epesaka ba événements personnalisés pona ba actions unique ya ba plugins mingi. Mingimingi, yango eyaka na lolenge ya infinitif mpe ya participe eleki - esika oyo infinitif (ex. show) ebandisami na ebandeli ya likambo moko, mpe lolenge na yango ya participe ya kala (ex. shown) ebandisami na bosilisi ya likambo moko.

Ba événements infinitifs nionso epesaka preventDefault()fonctionnalité. Yango epesaka makoki ya kopekisa exécution ya action moko avant ebanda. Kozongisa lokuta uta na mosaleli ya likambo ekobenga mpe automatiquement preventDefault().

var myModal = document.getElementById('myModal')

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

Makambo ya jQuery

Bootstrap eko détecter jQuery soki jQueryezali na kati ya windowobjet mpe ezali na data-bs-no-jqueryattribut moko te oyo etiamaki na <body>. Soki jQuery ezwami, Bootstrap ekobimisa ba événements grâce na système ya événement ya jQuery. Donc soki olingi koyoka ba événements ya Bootstrap, ekosengela osalela ba méthodes ya jQuery ( .on, .one) na esika ya addEventListener.

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

API ya programme

Ba constructeurs nionso bandimaka objet ya ba options optionnelles to eloko moko te (oyo ebandisaka plugin na comportement na yango par défaut):

var myModalEl = document.getElementById('myModal')

var modal = new bootstrap.Modal(myModalEl) // initialized with defaults
var modal = new bootstrap.Modal(myModalEl, { keyboard: false }) // initialized with no keyboard

Soki olingi kozwa instance ya plugin moko boye, plugin moko na moko ebimisaka getInstanceméthode moko. Mpo na kozwa yango mbala moko na eleman moko, salá boye: bootstrap.Popover.getInstance(myPopoverEl).

Ba selecteurs ya CSS na ba constructeurs

Okoki pe kosalela selecteur ya CSS lokola argument ya liboso na esika ya élément DOM pona ko initialiser plugin. Actuellement élément pona plugin ezwami na querySelectorméthode puisque ba plugins na biso esimbaka élément moko kaka.

var modal = new bootstrap.Modal('#myModal')
var dropdown = new bootstrap.Dropdown('[data-bs-toggle="dropdown"]')

Ba fonctions asynchrones na ba transitions

Ba méthodes nionso ya API programmatique ezali asynchrone mpe ezongaka na mobengi mbala moko transition ebandi kasi liboso esila .

Pona kosala action moko soki transition esili, okoki koyoka événement correspondant.

var myCollapseEl = document.getElementById('myCollapse')

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

En plus appel ya méthode na composante ya transition ekozala ignorée .

var myCarouselEl = document.getElementById('myCarousel')
var carousel = bootstrap.Carousel.getInstance(myCarouselEl) // Retrieve a Carousel instance

myCarouselEl.addEventListener('slid.bs.carousel', function (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 !!

Ba paramètres ya défaut

Okoki kobongola ba paramètres ya liboso ya plugin na kobongola Constructor.Defaulteloko ya plugin:

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

Conflit te (kaka soki osaleli jQuery)

Tango mosusu esengeli kosalela ba plugins ya Bootstrap na ba cadres mosusu ya UI. Na makambo oyo, bokutani ya esika ya nkombo ekoki kobima ntango mosusu. Soki likambo yango esalemi, okoki kobenga .noConflictplugin oyo olingi kozongisa motuya na yango.

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

Mituya ya ba versions

Version ya moko na moko ya ba plugins ya Bootstrap ekoki kozuama na nzela ya VERSIONpropriété ya constructeur ya plugin. Ndakisa, mpo na plugin ya tooltip:

bootstrap.Tooltip.VERSION // => "5.1.3"

Ba fallbacks ya sipesiale te tango JavaScript ezali désactivé

Ba plugins ya Bootstrap ezongaka sima te particulièrement gracement tango JavaScript ezali désactivé. Soki ozali komibanzabanza mpo na mayele ya mosaleli na likambo oyo, salelá <noscript>mpo na kolimbola likambo (mpe ndenge ya kofungola lisusu JavaScript) epai ya basaleli na yo, mpe/to kobakisa ba fallbacks na yo moko oyo olingi.

Babibliotɛkɛ ya bato mosusu

Bootstrap esungaka officiellement te ba bibliothèques ya JavaScript ya troisième partie lokola Prototype to jQuery UI. Malgré .noConflictmpe ba événements namespaced, ekoki kozala na ba problèmes ya compatibilité oyo esengeli o bongisa yo moko.

Sanitizer ya kosala

Tooltips na Popovers basalelaka sanitizer na biso intégré pona ko sanitiser ba options oyo endimaka HTML.

Motuya ya liboso allowListezali oyo elandi:

var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i
var 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: []
}

Soki olingi kobakisa ba valeurs ya sika na défaut allowListoyo okoki kosala oyo elandi:

var 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
var myCustomRegex = /^data-my-app-[\w-]+/
myDefaultAllowList['*'].push(myCustomRegex)

Soki olingi ko contourner sanitizer na biso po olingi kosalela bibliothèque dédiée, par exemple DOMPurify , esengeli osala oyo elandi:

var yourTooltipEl = document.getElementById('yourTooltip')
var tooltip = new bootstrap.Tooltip(yourTooltipEl, {
  sanitizeFn: function (content) {
    return DOMPurify.sanitize(content)
  }
})