JavaScript
Zisa iBootstrap ebomini ngeeplagi zethu ozikhethayo zeJavaScript. Funda malunga neplagin nganye, idatha yethu kunye nokhetho lweprogram ye-API, kunye nokunye.
Umntu ngamnye okanye uqokelelwe
Iiplagi zingabandakanywa ngabanye (usebenzisa iBootstrap's individual js/dist/*.js
), okanye zonke ngaxeshanye usebenzisa bootstrap.js
okanye iminified bootstrap.min.js
(ungaquki zombini).
Ukuba usebenzisa i-bundler (Webpack, Parcel, Vite…), ungasebenzisa /js/dist/*.js
iifayile ezilungele i-UMD.
Ukusetyenziswa ngeJavaScript yesakhelo
Ngelixa i-Bootstrap CSS ingasetyenziswa naso nasiphi na isakhelo, i-Bootstrap JavaScript ayihambelani ngokupheleleyo nesakhelo seJavaScript njengeReact, Vue, kunye ne-Angular ethatha ulwazi olupheleleyo lweDOM. Zombini i-Bootstrap kunye nesakhelo zinokuzama ukuguqula into enye ye-DOM, okukhokelela kwiibugs ezinjengokwehla okuthe nca kwindawo "evulekileyo".
Enye indlela ebhetele kwabo basebenzisa olu hlobo lwezakhelo kukusebenzisa isakhelo-impahla ethile endaweni yeBootstrap JavaScript. Nazi ezinye zeenketho ezidumileyo:
- Phendula: React Bootstrap
- I-Vue: I- BootstrapVue (okwangoku ixhasa kuphela i-Vue 2 kunye ne-Bootstrap 4)
- I- Angular: ng-bootstrap
Ukusebenzisa i-Bootstrap njengemodyuli
Sinikezela ngoguqulelo lweBootstrap eyakhiwe njenge ESM
( bootstrap.esm.js
kunye bootstrap.esm.min.js
) ekuvumela ukuba usebenzise iBootstrap njengemodyuli kwisikhangeli, ukuba iibhrawuza zakho ekujoliswe kuzo ziyayixhasa .
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
Xa kuthelekiswa ne-JS bundlers, ukusebenzisa i-ESM kwisikhangeli kufuna ukuba usebenzise indlela epheleleyo kunye negama lefayile endaweni yegama lemodyuli. Funda ngakumbi malunga neemodyuli ze-JS kwisikhangeli. Yiyo loo nto sisebenzisa 'bootstrap.esm.min.js'
endaweni 'bootstrap'
yangasentla. Nangona kunjalo, oku kunzima ngakumbi kukuxhomekeka kwethu kwePopper, engenisa iPopper kwiJavaScript yethu ngolu hlobo:
import * as Popper from "@popperjs/core"
Ukuba uzama oku njengokuba kunjalo, uya kubona impazamo kwi-console efana nale ilandelayo:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
Ukulungisa oku, ungasebenzisa i importmap
ukusombulula amagama emodyuli engenamkhethe ukugqiba umendo. Ukuba iibhrawuza zakho ekujoliswe kuzo azixhasi , importmap
kuya kufuneka usebenzise iprojekthi ye -es-module-shims . Nantsi indlela esebenza ngayo kwiBootstrap kunye nePopper:
<!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>
Ukuxhomekeka
Ezinye iiplagi kunye namalungu eCSS axhomekeke kwezinye iiplagi. Ukuba ubandakanya ii-plugins nganye, qiniseka ukuba ukhangele ezi zixhomekeke kumaxwebhu.
Iidrophu zethu, iipopovers, kunye netooltips nazo zixhomekeke kwiPopper .
Iimpawu zedatha
Phantse zonke iiplagi ze-Bootstrap zinokwenziwa kwaye ziqwalaselwe nge-HTML yodwa ngeempawu zedatha (indlela yethu esiyithandayo yokusebenzisa ukusebenza kweJavaScript). Qiniseka ukuba usebenzisa kuphela iseti enye yeempawu zedatha kwinto enye (umzekelo, awukwazi ukuvusa ingcebiso yesixhobo kunye nemodali ukusuka kwiqhosha elifanayo.)
Njengoko iinketho zinokugqithiswa ngeempawu zedatha okanye iJavaScript, unokongeza igama lokhetho ku data-bs-
, njengakwi data-bs-animation="{value}"
. Qinisekisa ukuba utshintshe uhlobo lwecala legama lokukhetha ukusuka kwi " camelCase " ukuya kwi " kebab-case " xa udlula iinketho ngeempawu zedatha. Umzekelo, sebenzisa data-bs-custom-class="beautifier"
endaweni ye- data-bs-customClass="beautifier"
.
Ukusukela kwi-Bootstrap 5.2.0, onke amacandelo axhasa umlinganiso wedatha ogciniweyo wovavanyodata-bs-config
onokubeka uqwalaselo lwecandelo olulula njengomtya we-JSON. Xa into ineempawu data-bs-config='{"delay":0, "title":123}'
kunye data-bs-title="456"
neempawu, ixabiso lokugqibela title
liya kuba 456
kunye neempawu zedatha eyahlukileyo ziya kuwenza ngaphezulu amaxabiso anikiweyo data-bs-config
. Ukongeza, iimpawu zedatha ezikhoyo ziyakwazi ukubeka ixabiso le-JSON njenge data-bs-delay='{"show":0,"hide":150}'
.
Abakhethi
Sisebenzisa imveli querySelector
kunye querySelectorAll
neendlela ukubuza izinto zeDOM ngezizathu zokusebenza, ke kufuneka usebenzise abakhethi abasebenzayo . Ukuba usebenzisa abakhethi abakhethekileyo njenge collapse:Example
, qiniseka ukuba uyabaleka.
Iziganeko
I-Bootstrap ibonelela ngeziganeko zesiko kwiintshukumo ezininzi ezizodwa zeeplagi. Ngokuqhelekileyo, ezi ziza ngendlela engapheliyo kunye neyexesha elidlulileyo - apho i-infinitive (umz. show
) iqaliswa ekuqaleni kwesiganeko, kwaye imo yaso yexesha elidlulileyo ye-participle (umz. shown
) ivuselelwe ekugqityweni kwesenzo.
Zonke iziganeko ezingapheliyo zibonelela preventDefault()
ngokusebenza. Oku kubonelela ukukwazi ukumisa ukuphunyezwa kwesenzo phambi kokuba siqale. Ukubuyisa okungeyonyani kumphathi wesiganeko nako kuyakufowunela ngokuzenzekelayo preventDefault()
.
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
Programmatic API
Bonke abakhi bamkela into ekhethiweyo yeenketho okanye akukho nto (eqalisa iplagin ngokuziphatha kwayo okungagqibekanga):
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
Ukuba ungathanda ukufumana umzekelo weplagin ethile, iplagin nganye iveza getInstance
indlela. Umzekelo, ukufumana umzekelo ngokuthe ngqo kwinto ethile:
bootstrap.Popover.getInstance(myPopoverEl)
Le ndlela iya kubuya null
ukuba umzekelo awuqaliswanga ngaphezulu kwento eceliweyo.
Kungenjalo, getOrCreateInstance
ingasetyenziselwa ukufumana umzekelo onxulunyaniswa nento yeDOM, okanye udale entsha ukuba ayikhange iqalwe.
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
Kwimeko apho umzekelo awuzange uqalise, inokwamkela kwaye isebenzise into ekhethwayo yoqwalaselo njengempikiswano yesibini.
Abakhethi beCSS kubakhi
Ukongeza kwiindlela getInstance
kunye getOrCreateInstance
neendlela, bonke abakhi beeplagi banokwamkela into yeDOM okanye umkhethi osebenzayo weCSS njengengxabano yokuqala. Izinto zeplagi zifumaneka kunye querySelector
nendlela kuba iiplagi zethu zixhasa kuphela into enye.
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 yeAsynchronous kunye notshintsho
Zonke iindlela zeprogram ye-API zi -asynchronous kwaye zibuyela kumnxebi xa utshintsho luqalisiwe, kodwa ngaphambi kokuba luphele . Ukuze wenze isenzo xa utshintsho lugqityiwe, ungamamela isiganeko esihambelanayo.
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
Ukongeza, ukufowunelwa kwendlela kwicandelo lenguquko kuya kuhoywa .
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
indlela
Nangona kunokubonakala kulungile ukusebenzisa dispose
indlela ngokukhawuleza emva koko hide()
, kuya kukhokelela kwiziphumo ezingalunganga. Nanku umzekelo wokusetyenziswa kwengxaki:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
Useto oluhlala lukhona
Ungatshintsha useto olungagqibekanga lweplagi ngokulungisa Constructor.Default
into yeplagin:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
Iindlela kunye neempawu
Yonke iplagin yeBootstrap iveza ezi ndlela zilandelayo kunye neempawu ezimileyo.
Indlela | Inkcazo |
---|---|
dispose |
Uyonakalisa imodali yento. (Isusa idatha egciniweyo kwisiqalelo seDOM) |
getInstance |
Indlela engatshintshiyo ekuvumela ukuba ufumane umzekelo wemodal odityaniswa nento yeDOM. |
getOrCreateInstance |
Indlela engatshintshiyo ekuvumela ukuba ufumane umzekelo wemodal onxulunyaniswa nento yeDOM, okanye wenze entsha ukuba ayiqalwanga. |
Ipropati engatshintshiyo | Inkcazo |
---|---|
NAME |
Ibuyisela igama le-plugin. (Umzekelo: bootstrap.Tooltip.NAME ) |
VERSION |
Uguqulelo lweplagi nganye yeBootstrap inokufikelelwa VERSION ngepropati yomakhi weplagi (Umzekelo bootstrap.Tooltip.VERSION :) |
Isicoci
Iingcebiso zezixhobo kunye neePopovers zisebenzisa isicoci esakhelwe ngaphakathi ukucoca iinketho ezamkela iHTML.
Ixabiso elimiselweyo allowList
lilandelayo:
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: []
}
Ukuba ufuna ukongeza amaxabiso amatsha koku kungagqibekanga allowList
ungenza oku kulandelayo:
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)
Ukuba ufuna ukudlula kwi-sanitizer yethu kuba ukhetha ukusebenzisa ithala leencwadi elizinikeleyo, umzekelo DOMpurify , kuya kufuneka wenze oku kulandelayo:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
Ngokukodwa usebenzisa i-jQuery
Awudingi i-jQuery kwi-Bootstrap 5 , kodwa kusenokwenzeka ukuba usebenzise amacandelo ethu ngejQuery. Ukuba i-Bootstrap ibhaqa jQuery
kwinto window
, iyakongeza onke amalungu ethu kwinkqubo yeplagi yejQuery. Oku kukuvumela ukuba wenze oku kulandelayo:
$('[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 kwamanye amacandelo ethu.
Akukho ngquzulwano
Ngamanye amaxesha kuyimfuneko ukusebenzisa iiplagi ze-Bootstrap kunye nezinye izikhokelo ze-UI. Kwezi meko, ukungqubana kwesithuba segama kunokwenzeka ngamanye amaxesha. Ukuba oku kuyenzeka, .noConflict
ungafowunela iplagin onqwenela ukubuyisela ixabiso layo.
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
I-Bootstrap ayizixhasi ngokusemthethweni iilayibrari zeJavaScript zomntu wesithathu njengePrototype okanye i-jQuery UI. Ngaphandle .noConflict
kweziganeko ezinamagama, kusenokubakho iingxaki zokuhambelana ekufuneka uzilungise wedwa.
Iziganeko zejQuery
I-Bootstrap iyakubona i-jQuery ukuba jQuery
ikhona window
kwinto kwaye akukho data-bs-no-jquery
phawu lusekiweyo <body>
. Ukuba i-jQuery ifunyenwe, i-Bootstrap izakukhupha iziganeko enkosi kwisixokelelwano somsitho wejQuery. Ke ukuba ufuna ukumamela iziganeko zeBootstrap, kuyakufuneka usebenzise iindlela zejQuery ( .on
, .one
) endaweni ye addEventListener
.
$('#myTab a').on('shown.bs.tab', () => {
// do something...
})
IJavaScript evaliweyo
Iiplagi zeBootstrap azinambuyiselo eyodwa xa iJavaScript ivaliwe. Ukuba unenkathalo ngamava omsebenzisi kule meko, sebenzisa <noscript>
ukuchaza imeko (kunye nendlela yokwenza kwakhona iJavaScript) kubasebenzisi bakho, kunye/okanye ukongeza okwakho ukusilela.