JavaScript
Zana Bootstrap mubuzima hamwe na plugin zacu za JavaScript. Wige kuri buri plugin, amakuru yacu hamwe na gahunda ya API ihitamo, nibindi byinshi.
Umuntu ku giti cye cyangwa yakusanyijwe
Amacomeka arashobora gushyirwamo kugiti cye (ukoresheje Bootstrap kugiti cye js/dist/*.js
), cyangwa byose icyarimwe ukoresheje bootstrap.js
cyangwa bigabanijwe bootstrap.min.js
(ntushyiremo byombi).
Niba ukoresheje bundler (Webpack, Parcelle, Vite…), urashobora gukoresha /js/dist/*.js
dosiye UMD yiteguye.
Imikoreshereze hamwe na JavaScript
Mugihe Bootstrap CSS ishobora gukoreshwa nurwego urwo arirwo rwose, Bootstrap JavaScript ntabwo ihuye neza nuburyo bwa JavaScript nka React, Vue, na Angular zifata ubumenyi bwuzuye kuri DOM. Byombi Bootstrap hamwe nurwego rushobora kugerageza guhindura ikintu kimwe cya DOM, bikavamo amakosa nkibitonyanga byometse kumwanya "ufunguye".
Ubundi buryo bwiza kubakoresha ubu bwoko bwibikorwa ni ugukoresha pake yihariye aho gukoresha Bootstrap JavaScript. Dore amwe mumahitamo azwi cyane:
- Igisubizo: Kora Bootstrap
- Agaciro: BootstrapVue (kuri ubu ishyigikira gusa Vue 2 na Bootstrap 4)
- Inguni: ng-bootstrap
Gukoresha Bootstrap nka module
Dutanga verisiyo ya Bootstrap yubatswe nka ESM
( bootstrap.esm.js
na bootstrap.esm.min.js
) igufasha gukoresha Bootstrap nka module muri mushakisha, niba mushakisha yawe igushigikiye .
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
Ugereranije na JS bundlers, ukoresheje ESM muri mushakisha biragusaba gukoresha inzira yuzuye nizina ryizina aho gukoresha izina rya module. Soma byinshi kubyerekeranye na JS muri mushakisha. Niyo mpamvu dukoresha 'bootstrap.esm.min.js'
aho gukoresha 'bootstrap'
hejuru. Ariko, ibi birarushijeho kugorana no kwishingikiriza kwa Popper, itumiza Popper muri JavaScript yacu nkiyi:
import * as Popper from "@popperjs/core"
Niba ugerageza ibi nkuko biri, uzabona ikosa muri konsole nkibi bikurikira:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
Kugira ngo ukosore ibi, urashobora gukoresha an importmap
kugirango ukemure amazina yuburyo butandukanye kugirango urangize inzira. Niba mushakisha yawe igenewe idashyigikiye importmap
, uzakenera gukoresha umushinga wa es-module-shims . Dore uko ikora kuri 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>
Kwishingikiriza
Amacomeka hamwe nibice bya CSS biterwa nandi macomeka. Niba ushizemo amacomeka kugiti cye, menya neza niba ugenzura ibyo biterwa muri doc.
Ibitonyanga byacu, popovers, hamwe nibikoresho byifashishwa na Popper .
Ibiranga amakuru
Hafi ya plugin zose za Bootstrap zirashobora gushobozwa no kugenwa binyuze muri HTML yonyine hamwe nibiranga amakuru (uburyo twahisemo bwo gukoresha imikorere ya JavaScript). Wemeze gukoresha gusa urutonde rwibintu biranga ikintu kimwe (urugero, ntushobora gukurura igikoresho na modal kuva kuri buto imwe.)
Nkuko amahitamo ashobora kunyuzwa kumurongo wamakuru cyangwa JavaScript, urashobora kongeramo izina ryamahitamo data-bs-
, nkuko biri data-bs-animation="{value}"
. Witondere guhindura ubwoko bwurubanza rwamahitamo kuva " ingamiya " kuri " kebab-urubanza " mugihe utambutsa amahitamo ukoresheje ibiranga amakuru. Kurugero, koresha data-bs-custom-class="beautifier"
aho data-bs-customClass="beautifier"
.
Nko muri Bootstrap 5.2.0, ibice byose bishyigikira igeragezwa ryibitse ryamakuru data-bs-config
rishobora kubamo ibice byoroshye nkibikoresho bya JSON. Mugihe ikintu gifite data-bs-config='{"delay":0, "title":123}'
nibiranga data-bs-title="456"
, agaciro kanyuma title
kazaba 456
kandi amakuru yihariye aranga agaciro katanzwe kuri data-bs-config
. Mubyongeyeho, amakuru ariho aranga arashobora kubika JSON indangagaciro nka data-bs-delay='{"show":0,"hide":150}'
.
Abatoranya
Dukoresha kavukire querySelector
nuburyo querySelectorAll
bwo kubaza ibintu bya DOM kubwimpamvu zikorwa, ugomba rero gukoresha abatoranya bemewe . Niba ukoresha abatoranya badasanzwe nka collapse:Example
, menya neza ko uzahunga.
Ibyabaye
Bootstrap itanga ibyabaye kubintu byinshi byacometse kubikorwa byihariye. Mubisanzwe, ibi biza muburyo butagira ingano kandi bwashize - aho infinitive (ex. show
) Itangizwa mugitangira ibirori, kandi ifishi yacyo ya kera (ex. shown
) Iterwa no kurangiza igikorwa.
Ibintu byose bitagira ingano bitanga preventDefault()
imikorere. Ibi bitanga ubushobozi bwo guhagarika ikorwa ryigikorwa mbere yuko gitangira. Garuka ibinyoma bivuye mubikorwa byabashinzwe nabo bazahita bahamagara preventDefault()
.
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
Gahunda ya API
Abubaka bose bemera ibintu bidahitamo ikintu cyangwa ntakindi (gitangiza plugin nimyitwarire isanzwe):
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
Niba ushaka kubona plugin runaka urugero, buri plugin yerekana getInstance
uburyo. Kurugero, kugarura urugero muburyo butaziguye:
bootstrap.Popover.getInstance(myPopoverEl)
Ubu buryo buzagaruka null
niba urugero rutatangijwe kubintu byasabwe.
Ubundi, getOrCreateInstance
irashobora gukoreshwa kugirango ubone urugero rujyanye nibintu bya DOM, cyangwa gukora urundi rushya mugihe rutatangijwe.
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
Mugihe urugero rutatangijwe, irashobora kwemera no gukoresha ikintu cyateganijwe nkimpaka ya kabiri.
Abatoranya CSS mububaka
Usibye uburyo getInstance
nuburyo getOrCreateInstance
, abubaka plugin bose barashobora kwemera ikintu cya DOM cyangwa uwatoranije CSS yemewe nkimpaka yambere. Amacomeka yabonetse hamwe nuburyo querySelector
kuva amacomeka yacu ashyigikira ikintu kimwe gusa.
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')
Imikorere ninzibacyuho
Uburyo bwa porogaramu zose za API nuburyo budahwitse kandi bugaruka kumuhamagara iyo inzibacyuho itangiye, ariko mbere yuko irangira . Kugirango ukore igikorwa iyo inzibacyuho irangiye, urashobora kumva ibyabaye.
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
Mubyongeyeho, uburyo bwo guhamagarira ibice byinzibacyuho bizirengagizwa .
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
buryo
Mugihe bisa nkaho ari byiza gukoresha dispose
uburyo ako kanya nyuma hide()
, bizaganisha kubisubizo bitari byo. Dore urugero rwo gukoresha ikibazo:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
Igenamiterere risanzwe
Urashobora guhindura igenamiterere risanzwe rya plugin uhindura Constructor.Default
ikintu cya plugin:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
Uburyo n'imiterere
Buri plugin ya Bootstrap yerekana uburyo bukurikira nibintu bihagaze.
Uburyo | Ibisobanuro |
---|---|
dispose |
Gusenya ikintu cyuburyo. (Kuraho amakuru yabitswe kubintu bya DOM) |
getInstance |
Uburyo buhagaze butuma ubona urugero rwerekana ibintu bifitanye isano na DOM. |
getOrCreateInstance |
Uburyo buhamye butuma ubona urugero rwuburyo bujyanye nibintu bya DOM, cyangwa gukora bundi bushya mugihe bitatangijwe. |
Umutungo uhagaze | Ibisobanuro |
---|---|
NAME |
Garuka izina rya plugin. (Urugero bootstrap.Tooltip.NAME :) |
VERSION |
Verisiyo ya buri plugin ya Bootstrap irashobora kugerwaho hifashishijwe VERSION umutungo wububiko bwa plugin (Urugero bootstrap.Tooltip.VERSION :) |
Isuku
Ibikoresho na popovers bikoresha ibikoresho byubatswe byubatswe kugirango dusukure amahitamo yemera HTML.
Agaciro allowList
gasanzwe ni ibi bikurikira:
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: []
}
Niba ushaka kongeramo indangagaciro kuriyi isanzwe allowList
urashobora gukora ibi bikurikira:
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)
Niba ushaka kurenga isuku yacu kuko uhisemo gukoresha isomero ryabigenewe, urugero DOMPurify , ugomba gukora ibi bikurikira:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
Ubishaka ukoresheje jQuery
Ntukeneye jQuery muri Bootstrap 5 , ariko biracyashoboka gukoresha ibice byacu hamwe na jQuery. Niba Bootstrap ibonye jQuery
mubintu window
, izongeramo ibice byose muri sisitemu ya plugin ya jQuery. Ibi biragufasha gukora ibi bikurikira:
$('[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
Kimwe nacyo kijyanye nibindi bice byacu.
Nta makimbirane
Rimwe na rimwe, birakenewe gukoresha amacomeka ya Bootstrap hamwe nibindi UI. Muri ibi bihe, umwanya wizina urashobora guhura rimwe na rimwe. Niba ibi bibaye, urashobora guhamagara .noConflict
kuri plugin wifuza guhindura agaciro ka.
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
Bootstrap ntabwo ishigikira kumugaragaro amasomero ya JavaScript ya gatatu nka Prototype cyangwa jQuery UI. Nubwo .noConflict
hamwe n'amazina yibyabaye, hashobora kubaho ibibazo byo guhuza ukeneye kwikemurira wenyine.
Ibyabaye
Bootstrap izamenya jQuery niba jQuery
ihari window
mubintu kandi nta data-bs-no-jquery
kiranga cyashyizweho <body>
. Niba jQuery ibonetse, Bootstrap izasohoza ibyabaye dukesha sisitemu y'ibyabaye bya jQuery. Niba rero ushaka kumva ibyabaye kuri Bootstrap, ugomba gukoresha uburyo bwa jQuery ( .on
, .one
) aho addEventListener
.
$('#myTab a').on('shown.bs.tab', () => {
// do something...
})
Yahagaritse JavaScript
Amacomeka ya Bootstrap ntagishobora gusubira inyuma mugihe JavaScript ihagaritswe. Niba witaye kuburambe bwabakoresha muriki kibazo, koresha <noscript>
kugirango usobanure uko ibintu bimeze (nuburyo bwo kongera gukora JavaScript) kubakoresha, kandi / cyangwa wongereho ibyo wiboneye.