JavaScript a ɛwɔ hɔ no
Fa Bootstrap ba nkwa mu denam yɛn JavaScript plugins a wopɛ no so. Sua plugin biara ho ade, yɛn data ne programmatic API a wobɛpaw, ne nea ɛkeka ho.
Ankorankoro anaasɛ wɔaboaboa ano
Wobetumi de plugins aka ho mmiako mmiako (fa Bootstrap's individual js/dist/*.js
), anaasɛ ne nyinaa prɛko pɛ de adi dwuma bootstrap.js
anaasɛ nea wɔayɛ no ketewaa bootstrap.min.js
(mfa abien no nyinaa nka ho).
Sɛ wode bundler (Webpack, Parcel, Vite...) di dwuma a, wubetumi de /js/dist/*.js
fael ahorow a ɛyɛ UMD ayɛ krado adi dwuma.
Sɛnea wɔde di dwuma ne JavaScript nhyehyɛe ahorow
Bere a wobetumi de Bootstrap CSS adi dwuma wɔ nhyehyɛe biara mu no, Bootstrap JavaScript no ne JavaScript nhyehyɛe ahorow te sɛ React, Vue, ne Angular a ɛfa no sɛ wonim DOM no ho nimdeɛ a edi mũ no nhyia koraa. Bootstrap ne framework no nyinaa betumi abɔ mmɔden sɛ wɔbɛsakra DOM element koro no ara, na ɛde mfomso ahorow te sɛ dropdowns a ɛbata “open” gyinabea no aba.
Ɔkwan pa a wɔbɛfa so ayɛ saa ama wɔn a wɔde saa nhyehyɛe yi di dwuma ne sɛ wɔde nhyehyɛe pɔtee bi bedi dwuma sen sɛ wɔde Bootstrap JavaScript bedi dwuma. Nneɛma a nkurɔfo ani gye ho kɛse no bi ni:
- Yɛ ho biribi: Yɛ ho biribi Bootstrap
- Vue: BootstrapVue (mprempren ɛboa Vue 2 ne Bootstrap 4 nkutoo)
- Angular: ng-bootstrap a ɛwɔ anim no
Bootstrap a wode bedi dwuma sɛ module
Yɛde Bootstrap no bi a wɔasi sɛ ESM
( bootstrap.esm.js
ne bootstrap.esm.min.js
) a ɛma wo kwan ma wode Bootstrap di dwuma sɛ module wɔ browser no mu ma, sɛ wo browser ahorow a wode w’ani asi so no boa a .
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
Sɛ wode toto JS bundlers ho a, ESM a wode bedi dwuma wɔ browser no mu no hwehwɛ sɛ wode ɔkwan mũ no nyinaa ne fael din di dwuma sen sɛ wode module din no bedi dwuma. Kenkan JS module ahorow ho nsɛm pii wɔ browser no mu. Ɛno nti na yɛde di dwuma 'bootstrap.esm.min.js'
sen sɛ yɛde bedi dwuma wɔ 'bootstrap'
atifi hɔ no. Nanso, eyi yɛ den bio esiane yɛn Popper a yɛde yɛn ho to so no nti, a ɛde Popper ba yɛn JavaScript mu te sɛ saa:
import * as Popper from "@popperjs/core"
Sɛ wosɔ eyi hwɛ sɛnea ɛte a, wubehu mfomso bi wɔ console no mu te sɛ nea edidi so yi:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
Sɛ wopɛ sɛ wosiesie eyi a, wubetumi de an importmap
asiesie module din ahorow a wopɛ no de awie akwan. Sɛ wo browser ahorow a wode w’ani asi so no ntumi mmoa importmap
, ɛho behia sɛ wode es-module-shims adwuma no di dwuma. Sɛnea ɛyɛ adwuma ma Bootstrap ne Popper ni:
<!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>
Nneɛma a wɔde wɔn ho to so
Plugin ne CSS afã horow bi gyina plugins afoforo so. Sɛ wode plugins ka ho mmiako mmiako a, hwɛ hu sɛ wobɛhwɛ saa dependencies yi wɔ docs no mu.
Yɛn dropdowns, popovers, ne tooltips nso gyina Popper so .
Data su ahorow
Ɛkame ayɛ sɛ wobetumi ama Bootstrap plugins nyinaa ayɛ adwuma na wɔahyehyɛ no denam HTML nkutoo so a ɛwɔ data su ahorow (ɔkwan a yɛpɛ a yɛfa so de JavaScript dwumadi di dwuma). Hwɛ sɛ wode data su ahorow biako pɛ bedi dwuma wɔ element biako so (sɛ nhwɛso no, wuntumi nhyɛ adwinnade ti ne modal mfi bɔtn koro no ara mu.)
Sɛnea wobetumi afa data attributes anaa JavaScript so de options no atwam no, wubetumi de option din ahyɛ data-bs-
, sɛnea ɛwɔ data-bs-animation="{value}"
. Hwɛ hu sɛ wobɛsesa case type a ɛwɔ option din no mu afi “ camelCase ” akɔ “ kebab-case ” bere a wode options no nam data attributes so retwam no. Sɛ nhwɛso no, fa di dwuma data-bs-custom-class="beautifier"
mmom sen sɛ wode data-bs-customClass="beautifier"
.
Ɛde besi Bootstrap 5.2.0 no, nneɛma no nyinaa boa nhwehwɛmu a wɔde asie data su data-bs-config
a ebetumi de afã nhyehyɛe a ɛnyɛ den ahyɛ mu sɛ JSON ahama. Sɛ element bi wɔ data-bs-config='{"delay":0, "title":123}'
ne data-bs-title="456"
su ahorow a, botae a etwa to title
no bɛyɛ 456
na data su ahorow a ɛtetew mu no bɛbɔ botae ahorow a wɔde ama wɔ data-bs-config
. Bio nso, data su ahorow a ɛwɔ hɔ dedaw no tumi de JSON botae ahorow te sɛ data-bs-delay='{"show":0,"hide":150}'
.
Nneɛma a wɔpaw
Yɛde native querySelector
ne querySelectorAll
akwan no di dwuma de bisa DOM elements esiane adwumayɛ nti, enti ɛsɛ sɛ wode selectors a ɛfata di dwuma . Sɛ wode selectors soronko te sɛ , di dwuma a collapse:Example
, hwɛ hu sɛ wubeguan afi wɔn ho.
Nsɛm a esisi
Bootstrap ma amanneɛbɔ nsɛm a esisi ma plugins dodow no ara nneyɛe soronko. Mpɛn pii no, eyinom ba wɔ asɛmfua a enni awiei ne adeyɛ a atwam mu - baabi a wɔde asɛmfua a enni awiei (ex. show
) no kanyan wɔ adeyɛ bi mfiase, na ne adeyɛ asɛm bi a atwam (ex. shown
) no fi ase bere a adeyɛ bi awie no.
Nsɛm a esisi a enni awiei nyinaa ma wotumi preventDefault()
yɛ adwuma. Eyi ma wotumi gyina adeyɛ bi a wɔyɛ no ano ansa na afi ase. Sɛ wosan de false fi event handler mu ba a, ɛno nso bɛfrɛ preventDefault()
.
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
Dwumadie API
Constructors nyinaa gye optional options object anaasɛ hwee (a ɛhyɛ plugin ase ne ne default suban):
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
Sɛ wopɛ sɛ wonya plugin nhwɛso pɔtee bi a, plugin biara da getInstance
ɔkwan bi adi. Sɛ nhwɛso no, sɛ wobɛgye nhwɛsoɔ bi afiri element bi mu tẽẽ a:
bootstrap.Popover.getInstance(myPopoverEl)
Saa kwan yi bɛsan aba null
sɛ wɔanhyɛ nhwɛsoɔ bi ase wɔ element a wɔabisa no so a.
Sɛnea ɛbɛyɛ a, getOrCreateInstance
wobetumi de adi dwuma de anya nhwɛso no a ɛbata DOM element bi ho, anaasɛ wɔayɛ foforo sɛ ebia wɔanhyɛ ase a.
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
Sɛ ɛba sɛ wɔanhyɛ nhwɛsoɔ bi ase a, ɛbɛtumi agye nhyehyɛɛ adeɛ a wopɛ na ɛde adi dwuma sɛ akasakasa a ɛtɔ so mmienu.
CSS selectors wɔ constructors mu
Wɔ getInstance
ne getOrCreateInstance
akwan no akyi no, plugin constructors nyinaa betumi agye DOM element anaa CSS selector a ɛfata sɛ akyinnyegye a edi kan. Plugin elements no wɔhunu ne querySelector
ɔkwan no ɛfiri sɛ yɛn plugins no boa element baako pɛ.
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 dwumadie ne nsakraeɛ
Programmatic API akwan nyinaa yɛ asynchronous na ɛsan kɔ nea ɔfrɛ no no nkyɛn bere a wɔafi nsakrae no ase no, nanso ansa na ɛbɛba awiei . Sɛnea ɛbɛyɛ a wobɛyɛ adeyɛ bi bere a nsakrae no awie no, wubetumi atie adeyɛ a ɛne no hyia no.
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
Bio nso, wobebu ani agu ɔkwan a wɔfa so frɛ ade bi a ɛresakra so no so .
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
ɔkwan
Bere a ebia ɛbɛyɛ te sɛ nea ɛteɛ sɛ wode dispose
ɔkwan no bedi dwuma wɔ , akyi pɛɛ no hide()
, ɛbɛma woanya nea ɛnteɛ. Ɔhaw a wɔde di dwuma ho nhwɛso ni:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
Nsiesiei ahorow a wɔahyɛ da ayɛ
Wubetumi asesa nhyehyɛe a wɔahyɛ da ayɛ ama plugin bi denam plugin no Constructor.Default
ade a wobɛsesa no so:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
Akwan ne nneɛma a ɛwɔ mu
Bootstrap plugin biara da akwan a edidi so yi ne static agyapade adi.
Ɔkwan | Nkyerɛmu |
---|---|
dispose |
Ɔsɛe element bi modal. (Eyi data a wɔde asie wɔ DOM element no so) |
getInstance |
Static kwan a ɛma wo kwan ma wo nya modal instance a ɛbata DOM element bi ho. |
getOrCreateInstance |
Static kwan a ɛma wo kwan ma wo nya modal instance a ɛbata DOM element bi ho, anaasɛ wobɔ foforo sɛ ɛba sɛ wɔanhyɛ aseɛ a. |
Static agyapade | Nkyerɛmu |
---|---|
NAME |
Sane de plugin din no ba. (Nhwɛso: bootstrap.Tooltip.NAME ) . |
VERSION |
Wobetumi afa VERSION plugin no constructor no agyapade so akɔ Bootstrap no plugins no mu biara version no so (Nhwɛso: bootstrap.Tooltip.VERSION ) . |
Nneɛma a wɔde tew nneɛma ho
Tooltips ne Popovers de yɛn sanitizer a wɔasisi no di dwuma de sanitize options a egye HTML.
Default allowList
value no ne nea edidi so yi:
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: []
}
Sɛ wopɛ sɛ wode values foforo ka default yi allowList
ho a wubetumi ayɛ nea edidi so yi:
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)
Sɛ wopɛ sɛ wutwa yɛn sanitizer no ho esiane sɛ wopɛ sɛ wode nhomakorabea a wɔatu ho ama di dwuma nti, sɛ nhwɛso no DOMPurify , ɛsɛ sɛ woyɛ nea edidi so yi:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
Sɛ wopɛ sɛ wode jQuery bedi dwuma a
Wonhia jQuery wɔ Bootstrap 5 , nanso ɛda so ara yɛ yiye sɛ wode yɛn afã horow no bedi dwuma ne jQuery. Sɛ Bootstrap hu jQuery
wɔ window
ade no mu a, ɛde yɛn afã horow no nyinaa bɛka ho wɔ jQuery no plugin nhyehyɛe no mu. Eyi ma wutumi yɛ nea edidi so yi:
$('[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
Saa ara na yɛn afã afoforo no nso te.
Ntawntawdi biara nni hɔ
Ɛtɔ da bi a ɛho hia sɛ wode Bootstrap plugins di dwuma ne UI frameworks afoforo. Wɔ saa tebea horow yi mu no, edin-ahunmu nhyiam betumi aba bere ne bere mu. Sɛ eyi ba a, wubetumi afrɛ .noConflict
plugin a wopɛ sɛ wosan de bo no ba no.
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
Bootstrap ntumi mmoa JavaScript nhomakorabea ahorow a ɛto so abiɛsa te sɛ Prototype anaa jQuery UI wɔ aban kwan so. Ɛmfa ho .noConflict
ne nsɛm a esisi a wɔde din ahyɛ mu no, ebia ɔhaw ahorow a ɛfa nhyiam ho wɔ hɔ a ɛsɛ sɛ w’ankasa wusiesie.
jQuery nsɛm a esisi
Bootstrap bɛhunu jQuery sɛ jQuery
ɛwɔ adeɛ no mu na attribute window
biara nni hɔ a wɔahyehyɛ wɔ . Sɛ wohu jQuery a, Bootstrap bɛma nsɛm a esisi no ada adi esiane jQuery nsɛm a esisi nhyehyɛe no nti. Enti sɛ wopɛ sɛ wotie Bootstrap nsɛm a esisi a, ɛsɛ sɛ wode jQuery akwan ( , ) di dwuma sen sɛ wode bedi dwuma .data-bs-no-jquery
<body>
.on
.one
addEventListener
$('#myTab a').on('shown.bs.tab', () => {
// do something...
})
Wɔagyae JavaScript no
Bootstrap no plugins no nni fallback soronko biara bere a wɔagyae JavaScript no. Sɛ wodwene dwumadiefoɔ suahunu ho wɔ saa asɛm yi mu a, fa <noscript>
kyerɛkyerɛ tebea no mu (ne sɛdeɛ wobɛsan ama JavaScript ayɛ adwuma) ama wo dwumadiefoɔ, ne/anaasɛ fa w’ankasa wo custom fallbacks ka ho.