JavaScript
Uripake Bootstrap kanthi plugin JavaScript opsional. Sinau babagan saben plugin, data lan opsi API terprogram, lan liya-liyane.
Individu utawa kompilasi
Plugins bisa dilebokake kanthi individu (nggunakake Bootstrap individu js/dist/*.js
), utawa kabeh bebarengan nggunakake bootstrap.js
utawa minified bootstrap.min.js
(ora kalebu loro-lorone).
Yen sampeyan nggunakake bundler (Webpack, Parcel, Vite…), sampeyan bisa nggunakake /js/dist/*.js
file sing siap UMD.
Panggunaan karo kerangka JavaScript
Nalika Bootstrap CSS bisa digunakake karo kerangka apa wae, Bootstrap JavaScript ora kompatibel karo kerangka JavaScript kaya React, Vue, lan Angular sing nganggep kawruh lengkap babagan DOM. Loro-lorone Bootstrap lan kerangka bisa nyoba mutasi unsur DOM sing padha, nyebabake kewan omo kaya dropdown sing macet ing posisi "mbukak".
Alternatif sing luwih apik kanggo sing nggunakake kerangka kerja iki yaiku nggunakake paket khusus kerangka tinimbang JavaScript Bootstrap. Ing ngisor iki sawetara opsi sing paling populer:
- React: React Bootstrap
- Vue: BootstrapVue (saiki mung ndhukung Vue 2 lan Bootstrap 4)
- Sudut: ng-bootstrap
Nggunakake Bootstrap minangka modul
Kita nyedhiyakake versi Bootstrap sing dibangun minangka ESM
( bootstrap.esm.js
lan bootstrap.esm.min.js
) sing ngidini sampeyan nggunakake Bootstrap minangka modul ing browser, yen browser sing ditargetake ndhukung .
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
Dibandhingake karo JS bundlers, nggunakake ESM ing browser mbutuhake sampeyan nggunakake path lengkap lan jeneng berkas tinimbang jeneng modul. Waca liyane babagan modul JS ing browser. Mulane kita nggunakake 'bootstrap.esm.min.js'
tinimbang 'bootstrap'
ndhuwur. Nanging, iki luwih rumit amarga ketergantungan Popper kita, sing ngimpor Popper menyang JavaScript kita kaya mangkene:
import * as Popper from "@popperjs/core"
Yen sampeyan nyoba iki, sampeyan bakal weruh kesalahan ing console kaya ing ngisor iki:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
Kanggo ndandani iki, sampeyan bisa nggunakake importmap
kanggo mutusake masalah jeneng modul kasepakatan kanggo ngrampungake path. Yen browser sing ditargetake ora ndhukung importmap
, sampeyan kudu nggunakake proyek es-module-shims . Mangkene cara kerjane kanggo Bootstrap lan 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>
Ketergantungan
Sawetara plugin lan komponen CSS gumantung ing plugin liyane. Yen sampeyan nyakup plugin kanthi individu, priksa manawa sampeyan mriksa dependensi kasebut ing dokumen kasebut.
dropdowns, popovers, lan tooltips kita uga gumantung ing Popper .
Atribut data
Saklawasé kabeh plugin Bootstrap bisa diaktifake lan dikonfigurasi liwat HTML kanthi atribut data (cara sing disenengi kanggo nggunakake fungsi JavaScript). Priksa manawa sampeyan mung nggunakake siji set atribut data ing siji unsur (contone, sampeyan ora bisa micu tooltip lan modal saka tombol sing padha.)
Minangka opsi bisa liwati liwat atribut data utawa JavaScript, sampeyan bisa nambah jeneng pilihan kanggo data-bs-
, kaya ing data-bs-animation="{value}"
. Priksa manawa kanggo ngganti jinis kasus jeneng pilihan saka " camelCase " kanggo " kebab-case " nalika ngliwati pilihan liwat atribut data. Contone, nggunakake data-bs-custom-class="beautifier"
tinimbang data-bs-customClass="beautifier"
.
Ing Bootstrap 5.2.0, kabeh komponen ndhukung atribut data sing dilindhungi eksperimendata-bs-config
sing bisa ngemot konfigurasi komponen sing prasaja minangka string JSON. Nalika unsur duwe data-bs-config='{"delay":0, "title":123}'
lan data-bs-title="456"
atribut, title
nilai pungkasan bakal 456
lan atribut data sing kapisah bakal ngilangi nilai sing diwenehake ing data-bs-config
. Kajaba iku, atribut data sing ana bisa ngemot nilai JSON kaya data-bs-delay='{"show":0,"hide":150}'
.
Pamilih
Kita nggunakake native querySelector
lan querySelectorAll
cara kanggo takon unsur DOM kanggo alasan kinerja, supaya sampeyan kudu nggunakake pamilih bener . Yen sampeyan nggunakake pamilih khusus kaya collapse:Example
, dadi manawa kanggo uwal saka wong-wong mau.
Acara
Bootstrap nyedhiyakake acara khusus kanggo umume tumindak unik plugin. Umumé, iki teka ing wangun infinitive lan past participle - ngendi infinitive (ex. show
) dipicu ing wiwitan acara, lan past participle wangun (ex. shown
) dipicu nalika completion saka tumindak.
Kabeh acara infinitive nyedhiyakake preventDefault()
fungsi. Iki menehi kemampuan kanggo mungkasi eksekusi tumindak sadurunge diwiwiti. Mbalik palsu saka panangan acara uga bakal nelpon kanthi otomatis preventDefault()
.
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
Programmatic API
Kabeh konstruktor nampa obyek opsional utawa ora ana apa-apa (sing miwiti plugin kanthi prilaku standar):
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
Yen sampeyan pengin njaluk conto plugin tartamtu, saben plugin mbukak getInstance
cara. Contone, kanggo njupuk conto langsung saka unsur:
bootstrap.Popover.getInstance(myPopoverEl)
Cara iki bakal bali null
yen conto ora diwiwiti liwat unsur sing dijaluk.
Utawa, getOrCreateInstance
bisa digunakake kanggo entuk conto sing ana gandhengane karo unsur DOM, utawa nggawe sing anyar yen ora diwiwiti.
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
Yen conto ora diwiwiti, bisa uga nampa lan nggunakake obyek konfigurasi opsional minangka argumen kapindho.
Pamilih CSS ing konstruktor
Saliyane metode getInstance
lan getOrCreateInstance
, kabeh konstruktor plugin bisa nampa unsur DOM utawa pamilih CSS sing bener minangka argumen pisanan. Unsur plugin ditemokake kanthi querySelector
cara amarga plugin kita mung ndhukung siji unsur.
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')
Fungsi lan transisi asinkron
Kabeh cara API programmatic ora sinkron lan bali menyang panelpon yen transisi diwiwiti, nanging sadurunge rampung . Kanggo nindakake tumindak sawise transisi rampung, sampeyan bisa ngrungokake acara sing cocog.
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
Kajaba iku, panggilan metode ing komponen transisi bakal diabaikan .
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
cara
Sanadyan koyone bener nggunakake dispose
cara kasebut sanalika sawise hide()
, bakal nyebabake asil sing salah. Mangkene conto panggunaan masalah:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
Setelan gawan
Sampeyan bisa ngganti setelan gawan kanggo plugin kanthi ngowahi Constructor.Default
obyek plugin:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
Metode lan sifat
Saben plugin Bootstrap mbukak cara lan sifat statis ing ngisor iki.
Metode | Katrangan |
---|---|
dispose |
Ngancurake modal unsur. (Mbusak data sing disimpen ing unsur DOM) |
getInstance |
Cara statis sing ngidini sampeyan entuk conto modal sing ana gandhengane karo unsur DOM. |
getOrCreateInstance |
Cara statis sing ngidini sampeyan entuk conto modal sing digandhengake karo unsur DOM, utawa nggawe sing anyar yen ora diwiwiti. |
Properti statis | Katrangan |
---|---|
NAME |
Ngasilake jeneng plugin. (Contone: bootstrap.Tooltip.NAME ) |
VERSION |
Versi saben plugin Bootstrap bisa diakses liwat VERSION properti konstruktor plugin kasebut (Contone: bootstrap.Tooltip.VERSION ) |
Sanitizer
Tooltips lan Popovers nggunakake sanitizer sing dibangun kanggo ngresiki opsi sing nampa HTML.
Nilai standar allowList
ing ngisor iki:
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: []
}
Yen sampeyan pengin nambah nilai anyar menyang standar iki, allowList
sampeyan bisa nindakake ing ngisor iki:
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)
Yen sampeyan pengin ngliwati sanitizer amarga luwih seneng nggunakake perpustakaan khusus, contone DOMPurify , sampeyan kudu nindakake ing ngisor iki:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
Opsional nggunakake jQuery
Sampeyan ora perlu jQuery ing Bootstrap 5 , nanging isih bisa nggunakake komponen kita karo jQuery. Yen Bootstrap ndeteksi obyek kasebut jQuery
, window
bakal nambah kabeh komponen ing sistem plugin jQuery. Iki ngidini sampeyan nindakake ing ngisor iki:
$('[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
Padha dadi kanggo komponen kita liyane.
Ora ana konflik
Kadhangkala perlu nggunakake plugin Bootstrap karo kerangka UI liyane. Ing kahanan kasebut, tabrakan spasi jeneng kadhangkala bisa kedadeyan. Yen kedadeyan kasebut, sampeyan bisa nelpon .noConflict
plugin sing pengin dibalekake regane.
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
Bootstrap ora resmi ndhukung perpustakaan JavaScript pihak katelu kaya Prototype utawa jQuery UI. Senadyan .noConflict
acara lan namespaced, bisa uga ana masalah kompatibilitas sing kudu didandani dhewe.
acara jQuery
Bootstrap bakal ndeteksi jQuery yen jQuery
ana ing window
obyek lan ora ana data-bs-no-jquery
atribut sing disetel <body>
. Yen jQuery ditemokake, Bootstrap bakal ngetokake acara thanks kanggo sistem acara jQuery. Dadi yen sampeyan pengin ngrungokake acara Bootstrap, sampeyan kudu nggunakake metode jQuery ( .on
, .one
) tinimbang addEventListener
.
$('#myTab a').on('shown.bs.tab', () => {
// do something...
})
JavaScript dipatèni
Plugins Bootstrap ora duwe fallback khusus nalika JavaScript dipateni. Yen sampeyan peduli karo pengalaman pangguna ing kasus iki, gunakake <noscript>
kanggo nerangake kahanan kasebut (lan carane ngaktifake JavaScript maneh) menyang pangguna, lan / utawa nambah fallbacks khusus sampeyan dhewe.