JavaScript
Hunza Bootstrap kuhupenyu neyedu sarudzo JavaScript plugins. Dzidza nezve plugin yega yega, data redu uye programmatic API sarudzo, nezvimwe.
Mumwe nemumwe kana kuunganidzwa
Mapulagi anogona kuverengerwa ega (uchishandisa Bootstrap's munhu js/dist/*.js
), kana zvese kamwechete uchishandisa bootstrap.js
kana minified bootstrap.min.js
(usasanganise ese ari maviri).
Kana iwe ukashandisa bundler (Webpack, Parcel, Viteā¦), unogona kushandisa /js/dist/*.js
mafaera akagadzirira UMD.
Kushandiswa neJavaScript maitiro
Kunyange iyo Bootstrap CSS inogona kushandiswa nechero chimiro, iyo Bootstrap JavaScript haienderane zvizere neJavaScript masisitimu seReact, Vue, uye Angular iyo inotora ruzivo ruzere rweDOM. Zvese zviri zviviri Bootstrap uye chimiro chinogona kuyedza kushandura chinhu chimwe chete cheDOM, zvichikonzera mabhugi senge madonhwe anonamira munzvimbo "yakavhurika".
Imwe nzira iri nani kune avo vanoshandisa rudzi urwu rwemafuremu ndeye kushandisa furemu-chaiyo package panzvimbo yeBootstrap JavaScript. Heano mamwe emhando dzakakurumbira sarudzo:
- React: React Bootstrap
- Vue: BootstrapVue (ikozvino inotsigira Vue 2 uye Bootstrap 4 chete)
- Angular: ng-bootstrap
Kushandisa Bootstrap semodule
Isu tinopa vhezheni yeBootstrap yakavakwa se ESM
( bootstrap.esm.js
uye bootstrap.esm.min.js
) iyo inokutendera kuti ushandise Bootstrap semodule mubrowser, kana mabhurawuza ako akatariswa akaitsigira .
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
Kuenzaniswa neJS bundlers, kushandisa ESM mubrowser inoda kuti iwe ushandise nzira yakazara uye filename panzvimbo yezita remodule. Verenga zvakawanda nezve JS modules mubrowser. Ndiko kusaka tichishandisa 'bootstrap.esm.min.js'
pachinzvimbo 'bootstrap'
chepamusoro. Nekudaro, izvi zvinowedzera kuomeswa nekutsamira kwedu kwePopper, iyo inopinza Popper muJavaScript yedu saizvozvo:
import * as Popper from "@popperjs/core"
Kana iwe ukaedza izvi sezvazviri, iwe uchaona kukanganisa mukoni sezvinotevera:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
Kuti ugadzirise izvi, unogona kushandisa a importmap
kugadzirisa ega emodule mazita kupedzisa nzira. Kana mabhurawuza ako akananga asingatsigire importmap
, unozofanirwa kushandisa es-module-shims purojekiti. Heano maitiro ainoshanda kuBootstrap uye 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>
Dependencies
Mamwe mapulagi uye CSS zvikamu zvinoenderana nemamwe mapulagi. Kana iwe ukasanganisira plugins wega, ita shuwa yekutarisa kune izvi zvinotsamira mumagwaro.
Kudonhedza kwedu, popovers, uye matipi ekushandisa zvakare zvinoenderana nePopper .
Data attribute
Anenge ese maBootstrap plugins anogona kugoneswa uye kugadziridzwa kuburikidza neHTML chete ane data hunhu (nzira yedu yatinoda yekushandisa JavaScript mashandiro). Iva nechokwadi chekushandisa seti imwe chete yedata hunhu pane chinhu chimwe chete (semuenzaniso, haugone kukonzeresa chetipi uye modal kubva pabhatani rimwechete.)
Sezvo sarudzo dzichigona kupfuudzwa kuburikidza nedata hunhu kana JavaScript, unogona kuisa sarudzo zita ku data-bs-
, semu data-bs-animation="{value}"
. Ita shuwa yekushandura mhando yekesi yezita resarudzo kubva ku " camelCase " kuenda ku " kebab-case " kana uchipfuura sarudzo kuburikidza ne data hunhu. Somuenzaniso, shandisa data-bs-custom-class="beautifier"
pane data-bs-customClass="beautifier"
.
Kubva kuBootstrap 5.2.0, zvese zvinongedzo zvinotsigira muyedzo wakachengetedzwa data hunhu data-bs-config
hunogona kuisa akareruka chechikamu kumisikidzwa setambo yeJSON. Kana chinhu chine data-bs-config='{"delay":0, "title":123}'
uye data-bs-title="456"
hunhu, kukosha kwekupedzisira title
kuchave 456
uye iyo yakaparadzana data hunhu inodarika kukosha kwakapihwa pa data-bs-config
. Pamusoro pezvo, hunhu huripo hwe data hunokwanisa kuisa hunhu hweJSON senge data-bs-delay='{"show":0,"hide":150}'
.
Selectors
Isu tinoshandisa zvemuno querySelector
uye querySelectorAll
nzira kubvunza zvinhu zveDOM nekuda kwezvikonzero zvekuita, saka unofanirwa kushandisa zvinosarudzwa zvinosarudzwa . Kana iwe ukashandisa akakosha anosarudza senge collapse:Example
, ita shuwa kutiza.
Zviitiko
Bootstrap inopa zviitiko zvetsika kune akawanda plugins 'akasarudzika zviito. Kazhinji, izvi zvinouya muchimiro chechirevo chisingaperi uye chekare - apo chisingaperi (ex. show
) chinotangwa pakutanga kwechiitiko, uye chimiro chayo chechirevo chekare (ex. shown
) chinotangwa pakupedzwa kwechiito.
Zvose zvisingagumi zviitiko zvinopa preventDefault()
kushanda. Izvi zvinopa kugona kumisa kuitwa kwechiito chisati chatanga. Kudzorera nhema kubva kumubati wechiitiko kuchafonawo otomatiki preventDefault()
.
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
Purogiramu yepurogiramu
Vese vavaki vanogamuchira sarudzo yesarudzo chinhu kana hapana (iyo inotanga plugin ine maitiro ayo akasarudzika):
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
Kana iwe uchida kuwana imwe plugin muenzaniso, imwe neimwe plugin inofumura getInstance
nzira. Semuenzaniso, kutora chiitiko zvakananga kubva kune chimwe chinhu:
bootstrap.Popover.getInstance(myPopoverEl)
Iyi nzira ichadzoka null
kana chiitiko chisina kutangwa pamusoro pechinhu chakumbirwa.
Neimwe nzira, getOrCreateInstance
inogona kushandiswa kuwana muenzaniso wakabatana neDOM element, kana kugadzira imwe nyowani kana isina kutangwa.
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
Kana chiitiko chisina kutangwa, chinogona kubvuma uye kushandisa sarudzo yekumisikidza chinhu senharo yechipiri.
CSS selectors mune vavaki
Pamusoro peiyo getInstance
uye getOrCreateInstance
nzira, vese vanogadzira plugin vanogona kugamuchira chinhu cheDOM kana cheCSS chakasarudzika senge nharo yekutanga. Plugin zvinhu zvinowanikwa neiyo querySelector
nzira sezvo maplugins edu achingotsigira chinhu chimwe chete.
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')
Asynchronous mabasa uye shanduko
Yese programmatic API nzira dzine asynchronous uye dzinodzokera kune anofona kana shanduko yatanga, asi isati yapera . Kuti uite chiito kana shanduko yapera, unogona kuteerera kune chiitiko chinoenderana.
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
Pamusoro pezvo, kufona kwenzira pachikamu chekuchinja kuchafuratirwa .
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
nzira
Kunyange zvingaite sezvakanaka kushandisa dispose
nzira nekukurumidza mushure hide()
, zvinotungamira kune zvisiri izvo. Heino muenzaniso wekushandiswa kwedambudziko:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
Default settings
Unogona kushandura zvigadziriso zveplugin nekugadzirisa chinhu cheplugin Constructor.Default
:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
Nzira uye zvivakwa
Yese Bootstrap plugin inofumura nzira dzinotevera uye static zvivakwa.
Nzira | Tsanangudzo |
---|---|
dispose |
Inoparadza modal yechinhu. (Inobvisa data rakachengetwa pachinhu cheDOM) |
getInstance |
Static nzira iyo inokutendera iwe kuti uwane iyo modal muenzaniso yakabatana neiyo DOM chinhu. |
getOrCreateInstance |
Static nzira iyo inokutendera iwe kuti uwane modal muenzaniso yakabatana neDOM chinhu, kana kugadzira imwe nyowani kana isina kutangwa. |
Static property | Tsanangudzo |
---|---|
NAME |
Inodzosa zita replugin. (Muenzaniso bootstrap.Tooltip.NAME :) |
VERSION |
Iyo vhezheni yeimwe neimwe yeBootstrap's plugins inogona kuwanikwa kuburikidza VERSION nemudziyo weiyo plugin muvaki (Muenzaniso bootstrap.Tooltip.VERSION :) |
Sanitizer
Maturusi uye Popovers anoshandisa yedu yakavakirwa-mukati sanitizer kuchenesa sarudzo dzinogamuchira HTML.
The default allowList
value ndeiyi inotevera:
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: []
}
Kana iwe uchida kuwedzera hutsva hutsva kune iyi default allowList
unogona kuita zvinotevera:
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)
Kana iwe uchida kupfuura yedu sanitizer nekuti unofarira kushandisa raibhurari yakatsaurirwa, semuenzaniso DOMpurify , unofanirwa kuita zvinotevera:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
Optionally kushandisa jQuery
Iwe haudi jQuery muBootstrap 5 , asi zvichiri kugona kushandisa zvikamu zvedu nejQuery. Kana Bootstrap ikaona jQuery
muchinhu window
, ichawedzera zvese zvezvikamu zvedu mujQuery's plugin system. Izvi zvinokubvumira kuita zvinotevera:
$('[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
Zvakafanana zvinoenda kune zvimwe zvikamu zvedu.
Hapana kunetsana
Dzimwe nguva zvinodikanwa kushandisa Bootstrap plugins nemamwe maUI maficha. Mumamiriro ezvinhu aya, kudhumhana kwemazita kunogona kuitika dzimwe nguva. Kana izvi zvikaitika, unogona kufonera .noConflict
plugin yaunoda kudzorera kukosha kwayo.
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
Bootstrap haitsigire zviri pamutemo maraibhurari echitatu-bato JavaScript sePrototype kana jQuery UI. Kunyangwe .noConflict
uye zviitiko zvakapatsanurwa mazita, panogona kunge paine matambudziko ekuenderana aunoda kugadzirisa wega.
jQuery zviitiko
Bootstrap ichaona jQuery kana jQuery
iripo window
muchinhu uye hapana data-bs-no-jquery
hunhu hwakaiswa pa <body>
. Kana jQuery yawanikwa, Bootstrap inoburitsa zviitiko nekuda kwejQuery's chiitiko system. Saka kana iwe uchida kuteerera zviitiko zveBootstrap, uchafanirwa kushandisa nzira dzejQuery ( .on
, .one
) pachinzvimbo che addEventListener
.
$('#myTab a').on('shown.bs.tab', () => {
// do something...
})
Yakavharwa JavaScript
Bootstrap's plugins haina chaiyo yekudzokera shure kana JavaScript yakadzimwa. Kana iwe uine hanya neruzivo rwemushandisi mune iyi kesi, shandisa <noscript>
kutsanangura mamiriro acho (uye maitiro ekuitazve JavaScript) kune vashandisi vako, uye/kana wedzera yako wega yekudonha.