JavaScript nisqa
Bootstrap kawsayman apamuy munasqa JavaScript pluginsniykuwan. Yachay sapa plugin kaqmanta, willayniykumanta chaymanta programatico API akllanakunamanta, chaymanta aswan.
Sapakama utaq huñusqa
Plugins sapalla churasqa kankuman (Bootstrap sapalla kaqninta llamk'achispa js/dist/*.js
), utaq tukuy huk kutillapi llamk'achispa bootstrap.js
utaq pisiyachisqa bootstrap.min.js
(ama iskayninta churaychu).
Sichus huk bundler (Webpack, Parcel, Vite...) llamk'achkanki, /js/dist/*.js
willañiqikunata llamk'achiy atikunki mayqinkunachus UMD wakichisqa kachkanku.
JavaScript marcokunawan llamk'achiy
Bootstrap CSS mayqin marco kaqwanpas llamk'achiy atikun chaypas, Bootstrap JavaScript mana hunt'asqachu JavaScript marcokunawan React, Vue, chaymanta Angular hina mayqinkunachus DOM kaqmanta hunt'asqa yachayta hap'inku. Iskaynin Bootstrap chaymanta marco kaqlla DOM elemento tikrayta munankuman, chaymanta pantasqakuna hina urmachiykuna “kichasqa” kaqpi wichq'asqa kachkanku.
Huk aswan allin alternativa kay laya marcokuna llamk'achiqkuna kaqpaq huk marco-específico paquete llamk'achiyta Bootstrap JavaScript kaqmanta. Kaypi wakin aswan riqsisqa akllanakuna kachkan:
- Reaccionar: Reaccionar Correa de Arranque
- Vue: BootstrapVue (kunan Vue 2 chaymanta Bootstrap 4 kaqlla yanapakun)
- Angular: ng-bootstrap nisqa
Bootstrap nisqata huk módulo hina llamk'achispa
ESM
Huk Bootstrap kaqmanta ( bootstrap.esm.js
chaymanta ) ruwasqa laya quyku bootstrap.esm.min.js
mayqinchus Bootstrap huk módulo hina maskaqpi llamk'achiyta saqin, sichus maskaqniyki maskaqkuna yanapanku .
<script type="module">
import { Toast } from 'bootstrap.esm.min.js'
Array.from(document.querySelectorAll('.toast'))
.forEach(toastNode => new Toast(toastNode))
</script>
JS huñusqakunawan tupachisqa, maskaqpi ESM llamk'achiyta hunt'a ñanta chaymanta willañiqi sutita llamk'achiyta munan, modulo sutimanta ranti. JS módulos kaqmanta astawan ñawiriy maskaqpi. Chayraykum hawapi nisqanchikpa 'bootstrap.esm.min.js'
rantinpi servichikunchik 'bootstrap'
. Ichaqa, kayqa aswan sasachakuyniyuq kachkan Popper dependenciaykuwan, mayqinchus Popperta JavaScriptniykuman chayhinata apamun:
import * as Popper from "@popperjs/core"
Sichus kayta imayna kasqanmanhina kallpachakunki, huk pantayta consolapi rikunki kayhina:
Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".
Kayta allichanapaq, huk llamk'achiy atikunki importmap
munasqa módulo sutikunata ñankuna hunt'anapaq allichanapaq. Sichus maskaqniykikuna munasqayki mana yanapankuchu importmap
, es-module-shims llamk'ayta llamk'achinayki tiyan. Kaypi imayna llamk'an Bootstrap chaymanta Popper kaqpaq:
<!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>
Dependenciakuna
Wakin plugins chaymanta CSS componentes wak plugins kaqmanta hapirin. Sichus sapalla plugins churanki, allinta qhaway kay dependenciakuna docs kaqpi.
Urmachiyniyku, popovers, chaymanta yanapakuyniykupas Popper kaqmanta hapirin .
Atributos de datos
Yaqa llapa Bootstrap plugins atichisqa chaymanta ruwasqa kanman sapalla HTML kaqninta willay layakunawan (ñawpaq munasqayku JavaScript ruwanakuna llamk'achiyta). Huk elementollapi huk huñu willay layakunallata llamk'achiy ( kayhina, mana huk yanapakuypa yuyaychayninta chaymanta modal kaqlla ñit'inamanta llamk'achiyta atikunkichu).
Imaynachus akllanakuna willay layakuna utaq JavaScript kaqninta pasayta atikun, huk akllana sutita yapayta atikunki kayman data-bs-
, imaynachus data-bs-animation="{value}"
. Aseguray akllana sutimanta caso laya “ camelCase ” kaqmanta “ kebab-case ” kaqman tikrayta mayk’aq akllanakunata atributos de datos kaqninta pasaspa. Ejemplopaq data-bs-custom-class="beautifier"
, data-bs-customClass="beautifier"
.
Bootstrap 5.2.0 kaqmanta, llapa componentakuna huk experimental waqaychasqa willay laya yanapakuyta yanapakunku data-bs-config
mayqinchus JSON watiqa hina sanu componente ruwayta wasichayta atin. Huk elemento data-bs-config='{"delay":0, "title":123}'
chaymanta data-bs-title="456"
layakunayuq kaqtin, qhipa title
chanin kanqa 456
chaymanta sapaq willay layakuna qusqa chanikunata llallichinqa data-bs-config
. Chaymanta, kunan kaq willay layakuna JSON chanikunata wasichayta atinku kayhina data-bs-delay='{"show":0,"hide":150}'
.
Akllaqkuna
Nativo querySelector
chaymanta querySelectorAll
métodos llamk'achiyku DOM elementokuna tapuypaq ruway razonkunarayku, chayrayku allin akllanakunata llamk'achinayki tiyan . Sichus akllaqkuna especialkunata llamk'achinki hina collapse:Example
, ama hina kaspa chaymanta ayqikuy.
Eventos nisqakuna
Bootstrap sapanchasqa ruwaykunata qun aswan plugins sapalla ruwanakuna kaqpaq. Tukuypaq, kaykunaqa mana tukukuq, ñawpaq participio nisqa rikch'aypi hamunku - maypichus infinitivo (ex. show
) huk suceso qallariypi llamk'achisqa, ñawpaq participio nisqa rikch'ayninqa (ex. shown
) huk ruway tukukuptin llamk'achisqa.
Llapan mana tukukuq sucesokuna preventDefault()
ruwayta qun. Kayqa huk ruwayta manaraq qallarichkaptin sayachiy atiyta qun. Huk suceso kamachiqmanta llulla kutichiypas kikinmanta waqyanqa preventDefault()
.
const myModal = document.querySelector('#myModal')
myModal.addEventListener('show.bs.modal', event => {
if (!data) {
return event.preventDefault() // stops modal from being shown
}
})
API programática nisqa
Llapan ruwaqkuna huk akllana akllanakuna objeto utaq mana imatapas chaskinku (mayqinchus huk plugin ñawpaqmanta ruwayninwan qallarichin):
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
Sichus huk particular plugin instanciata hap'iyta munanki, sapa plugin huk getInstance
métodota riqsichin. Ahinataq, huk elementomanta chiqap instanciata hurqunapaq:
bootstrap.Popover.getInstance(myPopoverEl)
Kay ñanqa kutimunqa null
sichus huk instancia mana mañasqa elemento patapi qallarisqachu.
Hukninpi, getOrCreateInstance
huk DOM elementowan tinkisqa instanciata hap'inapaq llamk'achiy atikun, utaq musuq ruwayta mana qallarisqa kaqtin.
bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)
Huk instancia mana qallarisqa kaqtinqa, huk akllana ruwanakuna iskay kaq argumento hina chaskinman chaymanta llamk'achinman.
Ruraqkunapi CSS akllaqkuna
getInstance
chaymanta getOrCreateInstance
ruwanakunamanta yapasqa , llapa plugin ruwaqkuna huk DOM elemento utaq huk allin CSS akllaq ñawpaq argumento hina chaskiyta atinku. Plugin elementokuna querySelector
métodowan tarikunku chaymanta pluginsniyku huk elementollata yanapanku.
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')
Funciones y transiciones asíncronas nisqakuna
Llapan programa API ruwanakuna asíncrono kanku chaymanta waqyaqman kutinku huk kuti tikray qallarisqa, ichaqa manaraq tukukuchkaptin . Huk kuti tikray tukusqaña huk ruwayta ruwanapaq, tupaq ruwayta uyariyta atikunki.
const myCollapseEl = document.querySelector('#myCollapse')
myCollapseEl.addEventListener('shown.bs.collapse', event => {
// Action to execute once the collapsible area is expanded
})
Chaymantapas, huk tikray componente kaqpi huk método waqyay mana qhawasqachu kanqa .
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
imayna
Sichus allin rikchakunman dispose
chaylla chay métodota llamk’achiyta hide()
, chaymanta mana allin ruwaykunata apamunqa. Kaypi huk rikch'ana sasachakuy llamk'achiyta:
const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous
myModal.addEventListener('shown.bs.hidden', event => {
myModal.dispose()
})
Ñawpaqmanta churasqakuna
Huk pluginpaq ñawpaqmanta churasqakunata tikrayta atikunki pluginpa Constructor.Default
objetonta tikraspa:
// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false
Métodos y propiedades
Sapa Bootstrap plugin kay qatiq ruwanakunata chaymanta mana kuyusqa propiedades nisqakunata riqsichin.
Imayna | Willay |
---|---|
dispose |
Huk elementopa modal nisqa kaynintam chinkachin. (DOM elementopi waqaychasqa willayta hurqun) |
getInstance |
Método estático kaqmanta mayqinchus huk DOM elementowan tinkisqa instancia modal kaqmanta jap'iyta atikun. |
getOrCreateInstance |
Método estático mayqinchus huk DOM elementowan tinkisqa modal instanciata hap'iyta atikun, utaq musuq ruwayta sichus mana qallarisqachu karqan. |
Propiedad estática nisqa | Willay |
---|---|
NAME |
Plugin sutita kutichin. (Ejemplo: bootstrap.Tooltip.NAME ) |
VERSION |
Sapa Bootstrap kaqpa pluginkunap laya kaqninman yaykuyta atikunman VERSION plugin ruwaqpa kaqnin kaqninta (Ejemplo: bootstrap.Tooltip.VERSION ) . |
Desinfectante
Tooltips chaymanta Popovers ruwasqayku desinfectanteykuta llamk'achinku akllanakunata chuyanchanapaq mayqinkunachus HTML chaskinku.
Ñawpaqmanta churasqa allowList
chaniqa kaymi:
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: []
}
Sichus kay ñawpaqmanta musuq chanikunata yapayta munanki kaykunata allowList
ruwayta atinki:
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)
Sichus desinfectanteykumanta pasayta munanki imaraykuchus huk dedicada biblioteca llamk'ayta munanki, kayhina DOMPurify , kaykunata ruwanayki tiyan:
const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
sanitizeFn(content) {
return DOMPurify.sanitize(content)
}
})
Opcionalmente utilizando jQuery
Mana jQuery kaqmanta Bootstrap 5 kaqpi necesitankichu , ichaqa atikunraqmi componentesniyku jQuery kaqwan llamk'achiyta. Sichus Bootstrap objeto jQuery
kaqpi tarin window
, llapa componentesniyku jQuery kaqpa plugin sistemanpi yapanqa. Chaynapim kaykunata ruwawaq:
$('[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
Chaynallataqmi wakin componentenchikkunapas.
Mana ch’aqwayniyuq
Wakin kutiqa huk UI marcokunawan Bootstrap plugins llamk'achina tiyan. Kayhina kaqtinqa, sutikunap chiqan t'inkinakuyninkuna wakin kutipi kanman. Sichus kay ruwakun, chay plugin kaqman waqyayta .noConflict
atikunki mayqinmantachus chanita kutichiyta munanki.
const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
Bootstrap mana oficialmente yanapanchu kimsa kaq JavaScript bibliotecakuna Prototype utaq jQuery UI hina. Aunque .noConflict
chaymanta sutikuna chiqanchasqa ruwaykuna, kanman tupachiy sasachakuykuna mayqinkunatachus sapallayki allichanayki tiyan.
jTapukuy ruwaykuna
Bootstrap jQuery kaqmanta tarinqa sichus objeto jQuery
kaqpi kachkan chaymanta mana atributo churasqa kanchu . Sichus jQuery tarikun, Bootstrap ruwaykunata kacharinqa jQuery kaqpa ruwana sistemanman gracias nispa. Chaymi sichus Bootstrap ruwaykunata uyariyta munanki, jQuery ruwanakunata ( , ) llamk'achinayki tiyan .window
data-bs-no-jquery
<body>
.on
.one
addEventListener
$('#myTab a').on('shown.bs.tab', () => {
// do something...
})
JavaScript nisqa mana llamk'achisqa
Bootstrap kaqpa plugins mana huk especial fallback kaqwanchu kanku JavaScript mana llamk'achisqa kaqtin. Sichus kay casopi ruwaqpa experiencianmanta llakikunki, llamk'achiy <noscript>
situacionta sut'inchanapaq (hinallataq imayna JavaScript kaqmanta atichiyta) ruwaqniykikunaman, chaymanta/utaq kikiyki ruwasqa fallbacksniyki yapay.