JavaScript
Ku soo dhawoow Bootstrap nolosheeda iyada oo la adeegsanayo furayaashayada JavaScript ee ikhtiyaarka ah. Baro plugin kasta, xogtayada iyo barnaamijyada API ikhtiyaarka ah, iyo in ka badan.
Shakhsi ama la ururiyey
Plugins si gaar ah ayaa loogu dari karaa (iyadoo la adeegsanayo shakhsi Bootstrap js/dist/*.js
), ama dhammaan hal mar la isticmaalayo bootstrap.js
ama la dhimay bootstrap.min.js
(ha ku darin labadaba).
Haddii aad isticmaasho xidhmo (Webpack, Parcel, Vite…), waxaad isticmaali kartaa /js/dist/*.js
faylasha UMD diyaar ah.
Isticmaalka qaab-dhismeedka JavaScript
Iyadoo Bootstrap CSS loo isticmaali karo qaab kasta, Bootstrap JavaScript si buuxda uma la jaanqaadi karo qaab-dhismeedka JavaScript sida React, Vue, iyo Angular kuwaas oo qaata aqoonta buuxda ee DOM. Labada Bootstrap iyo qaab-dhismeedka ayaa laga yaabaa inay isku dayaan inay beddelaan isla DOM element, taasoo ka dhalanaysa cayayaan sida hoos u dhaca ku dheggan booska "furan".
Beddelka ugu wanagsan ee kuwa isticmaalaya noocyada qaab-dhismeedka waa in ay adeegsadaan xirmo gaar ah oo qaab-dhismeedka halkii ay ka isticmaali lahaayeen Bootstrap JavaScript. Waa kuwan qaar ka mid ah xulashooyinka ugu caansan:
- Ka falcelin: Ka fal celi Bootstrap
- Vue: BootstrapVue (hadda waxay taageertaa kaliya Vue 2 iyo Bootstrap 4)
- Xaglaha: ng-bootstrap
Isticmaalka Bootstrap module ahaan
Waxaan bixinaa nooc ka mid ah Bootstrap loo dhisay sida ESM
( bootstrap.esm.js
iyo bootstrap.esm.min.js
) kaas oo kuu ogolaanaya inaad Bootstrap u isticmaasho modul browserka, haddii daalacashadaada la beegsanayo ay taageeraan .
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
Marka la barbar dhigo xidhmooyinka JS, adeegsiga ESM ee browser-ka waxa uu kaaga baahan yahay inaad isticmaasho dariiqa buuxa iyo magaca faylka halkii aad ka isticmaali lahayd magaca moduleka. Wax badan oo ku saabsan modules-ka JS ka akhri browserka. Taasi waa sababta aan u isticmaalno 'bootstrap.esm.min.js'
halkii 'bootstrap'
kor ku xusan. Si kastaba ha ahaatee, tani waxay sii dhibeysaa ku tiirsanaanta Popper, kaas oo Popper u soo dejinaya JavaScript-kayaga sida:
import * as Popper from "@popperjs/core"
Haddii aad isku daydo kan sida-uu yahay, waxaad ku arki doontaa cilad ku jirta console-ka sida tan soo socota:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
Si aad tan u xalliso, waxaad isticmaali kartaa importmap
si aad u xalliso magacyada cutubka aan sharciga ahayn si aad u dhamaystirto wadooyinka. Haddii daalacashadaada la beegsaday aysan taageerin importmap
, waxaad u baahan doontaa inaad isticmaasho mashruuca es-module-shims . Waa kan sida ay ugu shaqeyso Bootstrap iyo 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>
Ku-tiirsanaanta
Qaybaha qaar iyo qaybaha CSS waxay ku xidhan yihiin plugins kale. Haddii aad si gaar ah ugu darto plugins, hubi inaad hubiso waxyaalahan ku-tiirsanaanta dukumentiyada.
Hoos-u-dhacyadayada, popovers, iyo qalab-tilmaan-bixintayadu waxay sidoo kale ku xidhan yihiin Popper .
Sifooyinka xogta
Ku dhawaad dhammaan bootstrap plugins waa la awoodsiin karaa oo lagu habeyn karaa HTML oo keliya oo leh sifooyinka xogta (habka aan doorbideyno ee isticmaalka shaqeynta JavaScript). Hubi inaad isticmaasho hal sifo oo xogta ah oo keliya hal shay (tusaale, ma kicin kartid qalab iyo qaab isla badhanka.)
Sida xulashooyinka loogu gudbi karo sifooyinka xogta ama JavaScript, waxaad ku dari kartaa magaca ikhtiyaarka ah data-bs-
, sida ku jira data-bs-animation="{value}"
. Hubi inaad ka beddesho nooca kiis ee magaca ikhtiyaarka " camelCase " una beddelo " kebab-case " markaad ikhtiyaarka ku gudbinayso sifooyinka xogta. Tusaale ahaan, isticmaal data-bs-custom-class="beautifier"
bedelkii data-bs-customClass="beautifier"
.
Marka la eego Bootstrap 5.2.0, dhammaan qaybaha waxay taageeraan sifada xogta kaydsan ee tijaabadadata-bs-config
ah taas oo u dejin karta qaabaynta qaybaha fudud sida xadhig JSON ah. Marka curiye leeyahay data-bs-config='{"delay":0, "title":123}'
iyo data-bs-title="456"
sifooyin, title
qiimaha kama dambaysta ahi waxa uu ahaan doonaa 456
sifada xogta goonida ahina waxa ay meesha ka saari doontaa qiyamka lagu bixiyo data-bs-config
. Intaa waxaa dheer, sifada xogta hadda jirta waxay awood u leedahay inay ku noolaato qiyamka JSON sida data-bs-delay='{"show":0,"hide":150}'
.
Xulayaal
Waxaan u isticmaalnaa kuwa asalka ah querySelector
iyo querySelectorAll
hababka si aan u waydiino walxaha DOM sababo waxqabad dartood, marka waa inaad isticmaashaa xulashooyin sax ah . Haddii aad isticmaashid xulashooyin gaar ah sida collapse:Example
, hubi inaad ka baxsato.
Dhacdooyinka
Bootstrap waxay siisaa dhacdooyin caado u ah inta badan ficilada gaarka ah ee plugins. Guud ahaan, kuwani waxay ku yimaadaan qaab aan dhammaad lahayn oo hore uga qayb-qaatay-halkaas oo aan dhammaad lahayn (tusaale ahaan show
) uu kiciyo bilawga dhacdada, iyo qaabkeedii hore ee ka qaybqaadashada (tus. shown
) uu kiciyo marka ficilku dhammeeyo.
Dhammaan dhacdooyinka aan dhamaadka lahayn waxay bixiyaan preventDefault()
shaqeyn Tani waxay siinaysaa awoodda lagu joojinayo fulinta ficilka ka hor inta uusan bilaaban. Ka soo noqoshada beenta maamulaha dhacdada ayaa sidoo kale si toos ah u soo wici doona preventDefault()
.
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
API Programmatic
Dhammaan dhisayaashu waxay aqbalaan shay ikhtiyaari ikhtiyaari ah ama waxba (kaas oo bilaabaya plugin leh dabeecaddiisa caadiga ah):
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
Haddii aad jeclaan lahayd inaad hesho tusaale plugin gaar ah, plugin kastaa wuxuu daaha ka qaadayaa getInstance
hab. Tusaale ahaan, inaad si toos ah tusaale uga soo qaadato curiyaha:
bootstrap.Popover.getInstance(myPopoverEl)
Habkani wuu soo laaban doonaa null
haddii tusaale ahaan aan la bilaabin qaybta la codsaday.
Taas beddelkeeda, getOrCreateInstance
waxaa loo isticmaali karaa in lagu helo tusaale la xidhiidha curiyaha DOM, ama la abuuro mid cusub haddii aan la bilaabin.
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
Haddii tusaale aan la bilaabin, waxa laga yaabaa inay aqbasho oo ay isticmaasho shay qaabayn ikhtiyaari ah dood labaad.
Xulashada CSS ee dhisayaasha
Marka lagu daro hababka getInstance
iyo getOrCreateInstance
hababka, dhammaan dhisayaasha plugin waxay aqbali karaan walxaha DOM ama xulashada CSS sax ah sida doodda koowaad. Walxaha furaha waxaa laga helaa querySelector
habka maadaama pluginsyadayadu ay taageeraan hal shay.
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')
Hawlaha iyo kala-guurka asynchronous
Dhammaan hababka API-ga ee barnaamijka ah waa kuwo isku mid ah oo ku noqda soo wacaha marka kala-guurka la bilaabo, laakiin ka hor inta uusan dhammaan . Si aad ficil ufuliso marka kalaguurku dhamaado, waxaad dhagaysan kartaa dhacdada u dhiganta.
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
Intaa waxaa dheer, hab ku baaqaya in qayb ka beddelka waa la iska indhatiray .
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
habka
Iyadoo laga yaabo inay u muuqato mid sax ah in la isticmaalo dispose
habka isla markiiba ka dib hide()
, waxay u horseedi doontaa natiijooyin khaldan. Waa tan tusaale ka mid ah isticmaalka dhibaatada:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
Dejinta asalka ah
Waxaad ka beddeli kartaa habaynta caadiga ah ee plugin adiga oo wax ka beddelaya Constructor.Default
shayga plugin:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
Hababka iyo guryaha
Qalab kasta oo Bootstrap ah wuxuu daaha ka qaadaa hababka soo socda iyo sifooyinka taagan.
Habka | Sharaxaada |
---|---|
dispose |
Wuxuu baabi'iyaa habka curiyaha. (Waxay tirtirtaa xogta kaydsan ee cunta DOM) |
getInstance |
Habka taagan kaas oo kuu ogolaanaya inaad hesho tusaalaha moodeelka ee la xidhiidha curiyaha DOM. |
getOrCreateInstance |
Habka taagan kaas oo kuu ogolaanaya inaad hesho tusaalaha moodeelka ee la xidhiidha curiyaha DOM, ama abuurto mid cusub haddii aan la bilaabin. |
Hantida taagan | Sharaxaada |
---|---|
NAME |
Waxay soo celisaa magaca plugin (Tusaale bootstrap.Tooltip.NAME :) |
VERSION |
Nooca mid kasta oo ka mid ah bootstrap's plugins waxaa laga geli karaa VERSION hantida dhisaha plugin (Tusaale bootstrap.Tooltip.VERSION :) |
Nadiifiye
Aaladaha iyo Popovers waxay isticmaalaan nadiifiyaha ku dhex dhisan si ay u nadiifiyaan doorashooyinka aqbalaya HTML.
Qiimaha caadiga allowList
ah waa kan soo socda:
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: []
}
Haddii aad rabto inaad ku darto qiyamka cusub ee asalka ah allowList
waxaad samayn kartaa kuwan soo socda:
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)
Haddii aad rabto inaad dhaafto nadaafaddayada sababtoo ah waxaad doorbideysaa inaad isticmaasho maktabad gaar ah, tusaale ahaan DOMPurify , waa inaad sameyso waxyaabaha soo socda:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
Ikhtiyaar ahaan isticmaalaya jQuery
Uma baahnid jQuery gudaha Bootstrap 5 , laakiin wali waa suurtogal in la isticmaalo qaybahayada jQuery. Haddii Bootstrap jQuery
uu ku ogaado window
shayga, waxay ku dari doontaa dhammaan qaybahayada nidaamka plugin jQuery. Tani waxay kuu ogolaaneysaa inaad sameyso waxyaabaha soo socda:
$('[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
Waxa la mid ah qaybahayada kale.
Khilaaf ma jiro
Mararka qaarkood waa lagama maarmaan in la isticmaalo bootstrap plugins oo leh qaabab kale oo UI ah. Duruufahaan, isku dhacyada meel magac ayaa marmar dhici kara. Haddii tani dhacdo, waxaad wici .noConflict
kartaa plugin-ka aad rabto inaad dib u soo celiso qiimaha.
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
Bootstrap si rasmi ah uma taageerto qaybta saddexaad ee JavaScript maktabadaha sida Prototype ama jQuery UI. Iyadoo ay jiraan .noConflict
dhacdooyin magacyo kala duwan leh, waxaa laga yaabaa inay jiraan dhibaatooyin iswaafajin oo aad u baahan tahay inaad keligaa hagaajiso.
Dhacdooyinka jQuery
Bootstrap waxay ogaan doontaa jQuery haddii jQuery
ay ku jirto window
shayga oo aysan jirin data-bs-no-jquery
sifo lagu rakibay <body>
. Haddii jQuery la helo, Bootstrap ayaa soo dayn doonta dhacdooyinka iyadoo ay ugu wacan tahay nidaamka dhacdada jQuery. Markaa haddii aad rabto inaad dhegaysato dhacdooyinka Bootstrap, waa inaad isticmaashaa hababka jQuery ( .on
, .one
) halkii aad ka isticmaali lahayd addEventListener
.
$('#myTab a').on('shown.bs.tab', () => {
// do something...
})
JavaScript naafada ah
Bootstrap's plugins ma laha dib u dhac gaar ah marka JavaScript naafo yahay. Haddii aad danaynayso khibrada isticmaalaha kiiskan, isticmaal <noscript>
si aad u sharaxdo xaalada (iyo sida dib loogu soo celiyo JavaScript) isticmaalayaashaada, iyo/ama ku darso dib-u-dhacyadaada caadada ah.