JavaScript
Kawo Bootstrap zuwa rai tare da zaɓin plugins ɗin mu na JavaScript. Koyi game da kowane plugin, bayanan mu da zaɓuɓɓukan API na shirye-shirye, da ƙari.
Mutum ko harhada
Ana iya haɗa plugins daban-daban (ta yin amfani da mutum ɗaya na Bootstrap js/dist/*.js
), ko duka gaba ɗaya ta amfani da bootstrap.js
ko rage bootstrap.min.js
(kada ku haɗa duka biyun).
Idan kuna amfani da bundler (Webpack, Parcel, Vite…), zaku iya amfani da /js/dist/*.js
fayilolin da suke shirye UMD.
Amfani tare da tsarin JavaScript
Duk da yake ana iya amfani da Bootstrap CSS tare da kowane tsari, Bootstrap JavaScript bai dace da tsarin JavaScript kamar React, Vue, da Angular waɗanda ke ɗaukar cikakken ilimin DOM ba. Dukansu Bootstrap da tsarin na iya ƙoƙarin canza nau'in DOM iri ɗaya, yana haifar da kwari kamar zazzagewar da ke makale a matsayin "buɗe".
Mafi kyawun madadin waɗanda ke amfani da irin wannan nau'in tsarin shine yin amfani da takamaiman fakitin tsarin maimakon Bootstrap JavaScript. Ga wasu shahararrun zaɓuɓɓuka:
- Amsa: React Bootstrap
- Vue: BootstrapVue (a halin yanzu kawai yana goyan bayan Vue 2 da Bootstrap 4)
- Angular: ng-bootstrap
Amfani da Bootstrap azaman module
Muna ba da sigar Bootstrap da aka gina azaman ESM
( bootstrap.esm.js
da bootstrap.esm.min.js
) wanda ke ba ku damar amfani da Bootstrap azaman tsari a cikin burauzar, idan masu binciken ku da aka yi niyya suna tallafa masa .
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
Idan aka kwatanta da masu haɗa JS, yin amfani da ESM a cikin mai binciken yana buƙatar ku yi amfani da cikakken hanyar da sunan fayil maimakon sunan module. Kara karantawa game da samfuran JS a cikin burauzar. Shi ya sa muke amfani da 'bootstrap.esm.min.js'
maimakon 'bootstrap'
sama. Koyaya, wannan yana da rikitarwa ta hanyar dogaro da Popper, wanda ke shigo da Popper cikin JavaScript ɗin mu kamar haka:
import * as Popper from "@popperjs/core"
Idan kun gwada wannan kamar-isa, za ku ga kuskure a cikin na'ura mai kwakwalwa kamar haka:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
Don gyara wannan, zaku iya amfani da wani importmap
don warware sunaye na sabani don kammala hanyoyi. Idan masu binciken ku da aka yi niyya ba su goyi bayan importmap
, kuna buƙatar amfani da aikin es-module-shims . Anan ga yadda yake aiki don Bootstrap da 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>
Dogara
Wasu plugins da abubuwan CSS sun dogara da wasu plugins. Idan kun haɗa plugins daban-daban, tabbatar da bincika waɗannan abubuwan dogaro a cikin takaddun.
Zazzagewar mu, popovers, da tukwici na kayan aiki suma sun dogara da Popper .
Bayanan bayanai
Kusan duk Bootstrap plugins ana iya kunna su kuma daidaita su ta hanyar HTML kadai tare da halayen bayanai (hanyar da muka fi so ta amfani da ayyukan JavaScript). Tabbatar yin amfani da saitin sifofi guda ɗaya kawai akan kashi ɗaya (misali, ba za ku iya jawo tip ɗin kayan aiki da modal daga maɓalli ɗaya ba).
Kamar yadda za a iya wuce zaɓuɓɓuka ta hanyar sifofin bayanai ko JavaScript, zaku iya ƙara sunan zaɓi zuwa data-bs-
, kamar a cikin data-bs-animation="{value}"
. Tabbatar canza nau'in shari'ar sunan zaɓi daga " CamelCase " zuwa " kebab-case " lokacin ƙaddamar da zaɓuɓɓuka ta hanyar halayen bayanai. Misali, amfani data-bs-custom-class="beautifier"
maimakon data-bs-customClass="beautifier"
.
Dangane da Bootstrap 5.2.0, duk abubuwan da aka gyara suna goyan bayan sifa da aka keɓance na gwajidata-bs-config
wanda zai iya daidaita tsarin sassa mai sauƙi azaman kirtani JSON. Lokacin da kashi yana data-bs-config='{"delay":0, "title":123}'
da data-bs-title="456"
sifofi, title
ƙimar ƙarshe za ta kasance 456
kuma keɓantattun halayen bayanan za su soke ƙimar da aka bayar akan data-bs-config
. Bugu da ƙari, halayen bayanan da ke akwai suna iya ɗaukar ƙimar JSON kamar data-bs-delay='{"show":0,"hide":150}'
.
Masu zaɓe
Muna amfani da ƴan ƙasa querySelector
da querySelectorAll
hanyoyi don tambayar abubuwan DOM don dalilan aiki, don haka dole ne ku yi amfani da masu zaɓi masu inganci . Idan kuna amfani da masu zaɓe na musamman kamar collapse:Example
, tabbatar da kubuce musu.
Abubuwan da suka faru
Bootstrap yana ba da al'amuran al'ada don yawancin ayyuka na musamman na plugins. Gabaɗaya, waɗannan suna zuwa ne a cikin sigar ɓarna ta ƙarshe da ta gabata - inda ƙarshen (misali show
) ke haifar da shi a farkon wani lamari, kuma sigar ɓangarorinsa na baya (misali shown
) yana haifar da ƙarshen aikin.
Duk abubuwan da ba su da iyaka suna ba da preventDefault()
ayyuka. Wannan yana ba da ikon dakatar da aiwatar da wani aiki kafin ya fara. Koma karya daga mai kula da taron shima zai kira ta atomatik preventDefault()
.
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
API ɗin shirye-shirye
Duk masu ginin suna karɓar wani zaɓi na zaɓi ko ba komai (wanda ke fara plugin tare da dabi'un sa):
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
Idan kuna son samun misalin plugin ɗin, kowane plugin yana fallasa getInstance
hanya. Misali, don dawo da misali kai tsaye daga wani abu:
bootstrap.Popover.getInstance(myPopoverEl)
Wannan hanyar zata dawo null
idan ba'a fara misali akan abin da ake nema ba.
A madadin, getOrCreateInstance
ana iya amfani da shi don samun misalin da ke da alaƙa da abin DOM, ko ƙirƙirar sabo idan ba a fara shi ba.
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
Idan ba a fara wani misali ba, yana iya karɓa kuma yayi amfani da wani zaɓi na zaɓi azaman hujja ta biyu.
Masu zaɓen CSS a cikin ginin gini
Baya ga hanyoyin getInstance
da kuma getOrCreateInstance
hanyoyin, duk masu gina kayan aikin na iya karɓar kashi na DOM ko ingantaccen zaɓi na CSS azaman hujja ta farko. Ana samun abubuwan plugins tare da querySelector
hanyar tunda plugins ɗin mu suna goyan bayan kashi ɗaya kawai.
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')
Ayyukan asynchronous da canji
Duk hanyoyin API na shirye-shirye ba su daidaita ba kuma suna komawa ga mai kira da zarar an fara canji, amma kafin ya ƙare . Domin aiwatar da wani aiki da zarar an kammala canji, zaku iya sauraron abin da ya faru.
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
Bugu da ƙari, za a yi watsi da kiran hanya akan ɓangaren canji .
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
hanya
Duk da yake yana iya zama daidai don amfani da dispose
hanyar nan da nan bayan hide()
, zai haifar da sakamako mara kyau. Ga misalin amfani da matsalar:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
Saitunan tsoho
Kuna iya canza saitunan tsoho don plugin ta hanyar gyara abin plugin ɗin Constructor.Default
:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
Hanyoyi da kaddarorin
Kowane kayan aikin Bootstrap yana fallasa hanyoyin da ke biyowa da kaddarorin madaidaici.
Hanya | Bayani |
---|---|
dispose |
Yana lalata tsarin sinadari. (Yana cire bayanan da aka adana akan ɓangaren DOM) |
getInstance |
Hanyar a tsaye wacce ke ba ku damar samun misalan modal mai alaƙa da ɓangaren DOM. |
getOrCreateInstance |
Hanyar a tsaye wacce ke ba ka damar samun misalin tsarin da ke da alaƙa da abin DOM, ko ƙirƙirar sabo idan ba a fara shi ba. |
A tsaye dukiya | Bayani |
---|---|
NAME |
Yana dawo da sunan plugin. (Misali bootstrap.Tooltip.NAME :) |
VERSION |
Za a iya isa ga sigar kowane plugins na Bootstrap ta hanyar VERSION mallakar maginin plugin ɗin (Misali bootstrap.Tooltip.VERSION :) |
Sanitizer
Nasihun kayan aiki da Popovers suna amfani da ginanniyar sanitizer don tsabtace zaɓuɓɓukan da suka karɓi HTML.
Tsohuwar allowList
ƙimar ita ce mai zuwa:
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: []
}
Idan kuna son ƙara sabbin ƙima zuwa wannan tsoho allowList
za ku iya yin masu zuwa:
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)
Idan kuna son ketare sanitizer ɗinmu saboda kun fi son amfani da ɗakin karatu da aka keɓe, misali DOMPurify , yakamata kuyi masu zuwa:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
Zabi ta amfani da jQuery
Ba kwa buƙatar jQuery a cikin Bootstrap 5 , amma har yanzu yana yiwuwa a yi amfani da kayan aikin mu tare da jQuery. Idan Bootstrap ya gano jQuery
a cikin window
abu, zai ƙara duk abubuwan da aka haɗa a cikin tsarin plugin na jQuery. Wannan yana ba ku damar yin abubuwa masu zuwa:
$('[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
Haka yake ga sauran abubuwan da muka hada.
Babu rikici
Wani lokaci yana da mahimmanci a yi amfani da plugins Bootstrap tare da wasu tsarin UI. A cikin waɗannan yanayi, karon sararin samaniya na iya faruwa lokaci-lokaci. Idan wannan ya faru, kuna iya kiran .noConflict
plugin ɗin da kuke son mayar da darajar.
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
Bootstrap baya goyan bayan dakunan karatu na ɓangare na uku a hukumance kamar Prototype ko jQuery UI. Duk .noConflict
da abubuwan da aka raba suna, ana iya samun matsalolin daidaitawa waɗanda kuke buƙatar gyara da kanku.
abubuwan jQuery
Bootstrap zai gano jQuery idan jQuery
yana cikin window
abun kuma babu data-bs-no-jquery
sifa da aka saita akan <body>
. Idan an samo jQuery, Bootstrap zai fitar da abubuwan da suka faru godiya ga tsarin taron jQuery. Don haka idan kuna son sauraron abubuwan da suka faru na Bootstrap, dole ne ku yi amfani da hanyoyin jQuery ( .on
, .one
) maimakon addEventListener
.
$('#myTab a').on('shown.bs.tab', () => {
// do something...
})
An kashe JavaScript
Bootstrap's plugins ba su da koma baya na musamman lokacin da aka kashe JavaScript. Idan kuna kula da ƙwarewar mai amfani a wannan yanayin, yi amfani <noscript>
da bayanin halin da ake ciki (da kuma yadda ake sake kunna JavaScript) ga masu amfani da ku, da/ko ƙara naku faɗuwar al'ada.