JavaScript ezali
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.js
to oyo ekitisami bootstrap.min.js
(kokɔtisa nyonso mibale te).
Soki osaleli bundler (Webpack, Parcel, Vite...), okoki kosalela /js/dist/*.js
ba fichiers oyo ezali prêt ya UMD.
Kosalela na ba cadres ya JavaScript
Atako Bootstrap CSS ekoki kosalelama na cadre nionso, JavaScript ya Bootstrap ezali na boyokani mobimba te na ba cadres ya JavaScript lokola React, Vue, mpe Angular oyo ezuaka boyebi mobimba ya DOM. Ezala Bootstrap mpe cadre ekoki komeka kobongola élément DOM moko, kosala ete ba bugs lokola ba dropdowns oyo ekangami na position “ouverte”.
Lolenge mosusu ya malamu koleka mpo na baye basalelaka lolenge oyo ya ba cadres ezali kosalela paquet moko oyo etali cadre moko na esika ya JavaScript ya Bootstrap. Talá mwa makambo oyo bato mingi balingaka:
- Réagir: Réactionner na bootstrap
- Vue: BootstrapVue (lelo oyo ezali kosunga kaka Vue 2 mpe Bootstrap 4)
- Angulaire: ng-bobandi ya mosala
Kosalela Bootstrap lokola module
Tozali kopesa version ya Bootstrap oyo etongami lokola ESM
( bootstrap.esm.js
mpe bootstrap.esm.min.js
) oyo epesaka yo nzela ya kosalela Bootstrap lokola module na navigateur, soki ba navigateurs na yo oyo ozali ko cibler esungaka yango .
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
Soki tokokanisi yango na ba bundlers ya JS, kosalela ESM na navigateur esengi yo osalela nzela mobimba mpe kombo ya fisyé na esika ya kombo ya module. Tanga mingi na ntina ya ba modules ya JS na navigateur. Yango wana tosalelaka 'bootstrap.esm.min.js'
na esika ya 'bootstrap'
likolo. Kasi, yango ezali lisusu compliqué na dépendance na biso ya Popper, oyo ekotisaka Popper na JavaScript na biso lokola boye:
import * as Popper from "@popperjs/core"
Soki omeki oyo as-is, okomona erreur na console lokola oyo elandi:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
Mpo na kobongisa yango, okoki kosalela an importmap
mpo na kosilisa bankombo ya module arbitraire mpo na kosilisa banzela. Soki ba navigateurs na yo oyo ozali koluka esimbaka te importmap
, ekosɛnga osalela projet es-module-shims . Tala ndenge esalaka pona Bootstrap na 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>
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, mpe ba tolips ya bisaleli mpe etali Popper .
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.)
Lokola ba options ekoki koleka na nzela ya ba attributs ya ba données to JavaScript, okoki kobakisa kombo ya option na data-bs-
, lokola na data-bs-animation="{value}"
. Sala makasi o changer type ya cas ya kombo ya option depuis “ camelCase ” na “ kebab-case ” tango ozali koleka ba options via ba attributs ya ba données. Na ndakisa, salelá data-bs-custom-class="beautifier"
na esika ya data-bs-customClass="beautifier"
.
Kobanda na Bootstrap 5.2.0, ba composants nionso esungaka attribut ya ba données réservées expérimentalesdata-bs-config
oyo ekoki ko louer configuration ya composant simple lokola chaîne JSON. Tango élément moko ezali data-bs-config='{"delay":0, "title":123}'
na na ba data-bs-title="456"
attributs, valeur ya suka title
ekozala 456
mpe ba attributs ya ba données separates eko overrider ba valeurs oyo epesami na data-bs-config
. En plus, ba attributs ya ba données oyo ezali ezali capable ya ko louer ba valeurs JSON lokola data-bs-delay='{"show":0,"hide":150}'
.
Bato oyo baponaka
Tosalelaka native querySelector
mpe querySelectorAll
ba méthodes mpo na kotuna ba éléments DOM mpo na ba raisons ya performance, yango wana esengeli osalela ba sélecteurs valides . Soki osaleli ba sélecteurs spéciaux lokola collapse:Example
, sala 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 mobongisi ya likambo ekobenga mpe automatiquement preventDefault()
.
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
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):
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
Soki olingi kozwa instance ya plugin moko boye, plugin moko na moko ebimisaka getInstance
méthode moko. Ndakisa, mpo na kozwa instance mbala moko na eleman moko:
bootstrap.Popover.getInstance(myPopoverEl)
Méthode oyo ekozonga null
soki instance moko ebandi te likolo ya élément oyo esengi.
Na lolenge mosusu, getOrCreateInstance
ekoki kosalelama mpo na kozwa instance oyo esangisi na eleman ya DOM, to kosala ya sika na likambo oyo ebandaki te.
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
Na cas instance moko ebandaki te, ekoki kondima pe kosalela objet ya configuration optionnel lokola argument ya mibale.
Ba selecteurs ya CSS na ba constructeurs
En plus ya ba getInstance
méthodes na getOrCreateInstance
, ba constructeurs nionso ya plugin bakoki kondima élément DOM to sélecteur CSS valide lokola argument ya liboso. Ba éléments ya plugin ezwamaka na querySelector
méthode puisque ba plugins na biso esimbaka kaka élément moko.
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')
Ba fonctions asynchrones na ba transitions
Ba méthodes nionso ya API programmatique ezali asynchrone mpe ezongaka na mobengi mbala moko transition ebandi, kasi avant esila . Pona kosala action moko soki transition esili, okoki koyoka événement correspondant.
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
En plus, appel ya méthode na composante ya transition ekozala ignorée .
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 !!
dispose
metode
Atako ekoki komonana malamu kosalela dispose
mayele yango mbala moko nsima ya hide()
, ekosala ete bázwa matomba ya mabe. Tala ndakisa ya bosaleli ya mokakatano:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
Ba paramètres ya défaut
Okoki kobongola ba paramètres ya liboso ya plugin na kobongola Constructor.Default
eloko ya plugin:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
Méthodes na ba propriétés
Plugin nionso ya Bootstrap e exposer ba méthodes oyo elandi na ba propriétés statiques.
Metode | Ndimbola |
---|---|
dispose |
Ebebisaka modal ya élément moko. (Elongolaka ba données oyo ebombami na élément DOM) |
getInstance |
Méthode statique oyo e permettre yo ozua instance modal associée na élément DOM. |
getOrCreateInstance |
Méthode statique oyo e permettre yo ozua instance modal associée na élément DOM, to osala ya sika au cas où ezalaki initialisé te. |
Propriété statique | Ndimbola |
---|---|
NAME |
Ezongisaka kombo ya plugin. (Ndakisa: bootstrap.Tooltip.NAME ) . |
VERSION |
Version ya moko na moko ya ba plugins ya Bootstrap ekoki kozuama na nzela ya VERSION propriété ya constructeur ya plugin (Ndakisa: bootstrap.Tooltip.VERSION ) . |
Sanitizer ya kosala
Tooltips na Popovers basalelaka sanitizer na biso intégré pona ko sanitiser ba options oyo endimaka HTML.
Motuya ya liboso allowList
ezali oyo elandi:
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: []
}
Soki olingi kobakisa ba valeurs ya sika na défaut allowList
oyo okoki kosala oyo elandi:
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)
Soki olingi ko contourner sanitizer na biso po olingi kosalela bibliothèque dédiée, par exemple DOMPurify , esengeli osala oyo elandi:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
Na bolingi na yo kosalela jQuery
Ozali na mposa ya jQuery te na Bootstrap 5 , kasi ezali kaka na nzela ya kosalela ba composants na biso na jQuery. Soki Bootstrap e détecté jQuery
na window
objet, ekobakisa ba composants na biso nionso na système ya plugin ya jQuery. Yango epesaka yo nzela ya kosala makambo oyo elandi:
$('[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
Ezali mpe bongo mpo na biloko na biso mosusu.
Matata moko te
Tango mosusu esengeli kosalela ba plugins ya Bootstrap na ba cadres misusu ya UI. Na makambo oyo, bokutani ya esika ya nkombo ekoki kobima ntango mosusu. Soki likambo yango esalemi, okoki kobenga .noConflict
plugin oyo olingi kozongisa motuya na yango.
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
Bootstrap esungaka officiellement te ba bibliothèques ya JavaScript ya troisième partie lokola Prototype to jQuery UI. Malgré .noConflict
mpe ba événements namespaced, ekoki kozala na ba problèmes ya compatibilité oyo esengeli o bongisa yo moko.
Makambo ya jQuery
Bootstrap eko détecter jQuery soki jQuery
ezali na kati ya window
objet mpe ezali na data-bs-no-jquery
attribut 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', () => {
// do something...
})
JavaScript ekangami
Ba plugins ya Bootstrap ezalaka na fallback spécial te 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.