Tīpoka ki te ihirangi matua Tīpoka ki te whakaterenga tuhinga
Check
in English

JavaScript

Whakaorangia a Bootstrap me o maatau taputapu JavaScript. Akohia mo ia mono, o maatau raraunga me nga whiringa API papatono, me etahi atu.

Takitahi, whakahiato ranei

Ka taea te whakauru takitahi nga monomai (ma te whakamahi i te tangata takitahi a Bootstrap js/dist/*.js), me te katoa i te wa kotahi ma te whakamahi bootstrap.js, te iti ranei bootstrap.min.js(kaua e whakaurua e rua).

Mena kei te whakamahi koe i te paihere (Webpack, Parcel, Vite…), ka taea e koe te whakamahi i /js/dist/*.jsnga konae kua rite te UMD.

Te whakamahi me nga angamahi JavaScript

Ahakoa ka taea te whakamahi i te Bootstrap CSS me tetahi anga, ko te Bootstrap JavaScript kaore i te tino hototahi ki nga anga JavaScript penei i React, Vue, me Angular e mau ana i te mohiotanga ki te DOM. Ka ngana pea a Bootstrap me te anga ki te whakarereke i te huānga DOM kotahi, ka puta mai nga pepeke penei i nga takaiho ka mau ki te waahi "tuwhera".

Ko te mea pai ake mo te hunga e whakamahi ana i tenei momo anga ko te whakamahi i tetahi kete anga-motuhake hei utu mo te Bootstrap JavaScript. Anei etahi o nga whiringa tino rongonui:

Te whakamahi i te Bootstrap hei kōwae

Whakamātauria koe! Tikiake i te waehere puna me te demo mahi mo te whakamahi i a Bootstrap hei kōwae ES mai i te rehitatanga twbs/tauira . Ka taea hoki e koe te whakatuwhera i te tauira i StackBlitz .

Ka whakaratohia e matou he putanga o Bootstrap i hangaia hei ESM( bootstrap.esm.jsme bootstrap.esm.min.js) e taea ai e koe te whakamahi i a Bootstrap hei kōwae i roto i te tirotiro, mena ka tautokohia e to kaitirotiro kua tohua .

<script type="module">
  import { Toast } from 'bootstrap.esm.min.js'

  Array.from(document.querySelectorAll('.toast'))
    .forEach(toastNode => new Toast(toastNode))
</script>

Ka whakatauritea ki nga paihere JS, ma te whakamahi i te ESM i roto i te tirotiro me whakamahi koe i te ara katoa me te ingoa konae hei utu mo te ingoa kōwae. Pānuihia atu mo nga waahanga JS i roto i te tirotiro. Koinei te take ka whakamahia e matou i 'bootstrap.esm.min.js'runga 'bootstrap'ake nei. Heoi, he uaua ake tenei na to tatou whakawhirinakitanga Popper, e kawemai ana a Popper ki roto i a tatou JavaScript penei:

import * as Popper from "@popperjs/core"

Mena ka whakamatau koe i tenei ahua, ka kite koe i tetahi hapa i roto i te papatohu penei:

Uncaught TypeError: Failed to resolve module specifier "@popperjs/core". Relative references must start with either "/", "./", or "../".

Hei whakatika i tenei, ka taea e koe te whakamahi i te importmapki te whakatau i nga ingoa o nga waahanga hei whakaoti i nga huarahi. Ki te kore e tautokohia e ou kaitirotiro kua tohuaimportmap , me whakamahi koe i te kaupapa es-module-shims . Anei te mahi mo Bootstrap me 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>

Nga whakawhirinakitanga

Ko etahi mono me nga waahanga CSS e whakawhirinaki ana ki etahi atu mono. Mena kei te whakauru takitahi koe i nga monomai, tirohia te tirotiro mo enei whakawhirinaki i roto i nga tuhinga.

Ka whakawhirinaki ano a maatau whakahekenga, pouvers, me a maatau taputapu ki te Popper .

Nga huanga raraunga

Tata ki te katoa o nga taputapu Bootstrap ka taea te whakahohe me te whirihora ma te HTML anake me nga huanga raraunga (ko ta matou huarahi pai ki te whakamahi i te mahi JavaScript). Kia mau ki te whakamahi i tetahi huinga huanga raraunga i runga i te huānga kotahi (hei tauira, kaore e taea e koe te whakaoho i te aki taputapu me te aratau mai i te paatene kotahi.)

I te mea ka tukuna nga whiringa ma nga huanga raraunga, JavaScript ranei, ka taea e koe te taapiri i tetahi ingoa whiringa ki data-bs-, penei i te data-bs-animation="{value}". Kia mohio koe ki te whakarereke i te momo keehi o te ingoa whiringa mai i te " CamelCase " ki te " kebab-case " ka tukuna nga whiringa ma nga huanga raraunga. Hei tauira, whakamahia data-bs-custom-class="beautifier"hei utu mo data-bs-customClass="beautifier".

Mai i te Bootstrap 5.2.0, ka tautoko nga waahanga katoa i tetahi huanga raraunga kua rahuitia hei whakamatautaudata-bs-config ka taea te whakanoho i te whirihoranga waahanga ngawari hei aho JSON. Ina he huānga data-bs-config='{"delay":0, "title":123}'me data-bs-title="456"nga huanga, ko te titleuara whakamutunga 456ko nga huanga raraunga motuhake ka takahia nga uara kua hoatu ki runga data-bs-config. I tua atu, ka taea e nga huanga raraunga o mua te whakanoho i nga uara JSON penei i te data-bs-delay='{"show":0,"hide":150}'.

Kaiwhiriwhiri

Ka whakamahia e matou nga tikanga taketake querySelectorme querySelectorAllnga tikanga ki te uiui i nga huānga DOM mo nga take mahi, na me whakamahi koe i nga kaiwhiri whaimana . Mena ka whakamahi koe i nga kaikowhiri motuhake penei i a collapse:Example, kia mawhiti atu koe.

Nga huihuinga

Ka whakarato a Bootstrap i nga huihuinga ritenga mo te nuinga o nga mahi ahurei. Ko te tikanga, ka puta mai enei i roto i te ahua whai mutunga me te ahua o mua - kei reira te infinitive (ex. show) ka puta i te timatanga o te takahanga, a ko tona puka participle o mua (ex. shown) ka puta i te otinga o te mahi.

Ko nga huihuinga mutunga kore e whakarato preventDefault()taumahinga. Ka whai waahi tenei ki te aukati i te mahi i mua i te tiimata. Ko te whakahoki teka mai i te kaikawe takahanga ka waea aunoa preventDefault().

const myModal = document.querySelector('#myModal')

myModal.addEventListener('show.bs.modal', event => {
  if (!data) {
    return event.preventDefault() // stops modal from being shown
  }
})

API Papatono

Ka whakaaehia e nga kaihanga katoa he ahanoa hei kowhiringa, kaore ranei (e timata ana i te mono me tana whanonga taunoa):

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

Mena kei te pirangi koe ki te tiki i tetahi tauira mono, ka whakaatuhia e ia mono he getInstancetikanga. Hei tauira, ki te tiki i tetahi tauira mai i tetahi huānga:

bootstrap.Popover.getInstance(myPopoverEl)

Ka hoki mai tenei tikanga nullki te kore e timatahia he tauira i runga i te huānga i tonoa.

Ka getOrCreateInstancetaea te whakamahi ki te tiki i te tauira e hono ana ki tetahi huānga DOM, ki te hanga i tetahi mea hou mena kaore i arawhitia.

bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)

Mena karekau he tauira i arawhiti, ka whakaaehia ka whakamahi i tetahi ahanoa whirihoranga hei tohenga tuarua.

Kaihoko CSS i roto i nga kaihanga

I tua atu i nga tikanga getInstanceme nga tikanga, ka taea e nga kaihanga mono katoa te whakaae ki tetahi huānga DOM, he kaiwhiri CSSgetOrCreateInstance whaimana ranei hei tohenga tuatahi. Ka kitea nga huānga monomai me te tikanga na te mea ka tautoko noa a maatau mono i te huānga kotahi.querySelector

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')

Nga mahi tukutahi me nga whakawhitinga

Ko nga tikanga API hotaka katoa he tukutahi ka hoki ki te kaiwaea ina timata te whakawhiti, engari i mua i te mutunga . Hei mahi i tetahi mahi ina oti te whakawhitinga, ka taea e koe te whakarongo ki te kaupapa e pa ana.

const myCollapseEl = document.querySelector('#myCollapse')

myCollapseEl.addEventListener('shown.bs.collapse', event => {
  // Action to execute once the collapsible area is expanded
})

I tua atu, ka warewarehia te karanga tikanga mo tetahi waahanga whakawhiti .

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 !!

disposetikanga

Ahakoa te ahua tika ki te whakamahi i te disposetikanga i muri tonu mai hide(), ka puta he hua. Anei tetahi tauira o te whakamahi raru:

const myModal = document.querySelector('#myModal')
myModal.hide() // it is asynchronous

myModal.addEventListener('shown.bs.hidden', event => {
  myModal.dispose()
})

Tautuhinga taunoa

Ka taea e koe te huri i nga tautuhinga taunoa mo te mono ma te whakarereke i te Constructor.Defaultahanoa o te mono:

// changes default for the modal plugin's `keyboard` option to false
bootstrap.Modal.Default.keyboard = false

Nga tikanga me nga taonga

Ko ia mono Bootstrap e whakaatu ana i nga tikanga e whai ake nei me nga ahuatanga pateko.

Tikanga Whakaahuatanga
dispose Ka whakakore i te ahua o te huānga. (Tangohia ai nga raraunga rongoa i te huānga DOM)
getInstance Tikanga pateko e taea ai e koe te tiki i te tauira aratau e hono ana ki tetahi huānga DOM.
getOrCreateInstance Tikanga pateko e taea ai e koe te tiki i te tauira aratau e hono ana ki tetahi huānga DOM, ki te hanga i tetahi mea hou mena kaore i arawhitia.
Taonga pateko Whakaahuatanga
NAME Ka whakahoki i te ingoa mono. (Tauira: bootstrap.Tooltip.NAME)
VERSION Ko te putanga o ia monomai a Bootstrap ka taea te uru ma te VERSIONtaonga o te kaihanga o te mono (Tauira: bootstrap.Tooltip.VERSION)

Kaihoroi

Ko nga Aki Utauta me nga Popovers e whakamahi ana i ta maatau kai horoi ki te horoi i nga whiringa ka whakaae ki te HTML.

allowListKo te uara taunoa e whai ake nei:

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: []
}

Mena kei te hiahia koe ki te taapiri i nga uara hou ki tenei taunoa allowListka taea e koe te mahi:

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)

Mena kei te pirangi koe ki te karo i ta maatau kai horoi na te mea he pai ki a koe ki te whakamahi i te whare pukapuka whakatapua, hei tauira DOMPuify , me mahi e koe enei e whai ake nei:

const yourTooltipEl = document.querySelector('#yourTooltip')
const tooltip = new bootstrap.Tooltip(yourTooltipEl, {
  sanitizeFn(content) {
    return DOMPurify.sanitize(content)
  }
})

Ma te whakamahi i te jQuery

Kaore koe e hiahia jQuery i Bootstrap 5 , engari ka taea tonu te whakamahi i o maatau waahanga me te jQuery. Mena ka kitea e Bootstrap jQueryi roto i te windowahanoa, ka taapiri katoa o maatau waahanga ki te punaha mono a jQuery. Ma tenei ka taea e koe te mahi i nga mea e whai ake nei:

$('[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

He pera ano mo etahi atu waahanga.

Karekau he pakanga

I etahi wa ka tika te whakamahi i nga taputapu Bootstrap me etahi atu anga UI. I roto i enei ahuatanga, ka taea e nga tukinga mokowā ingoa i etahi wa. Mena ka pa tenei, ka waea atu koe .noConflictki te mono e hiahia ana koe ki te whakahoki i te uara o.

const bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality

Kaore a Bootstrap e tautoko mana i nga whare pukapuka JavaScript tuatoru penei i te Prototype, jQuery UI ranei. Ahakoa .noConflictnga huihuinga me te mokowhiti ingoa, tera pea he raruraru hototahi hei whakatika maau ake.

nga kaupapa jQuery

Ka kitea e Bootstrap te jQuery mena jQuerykei roto i te windowahanoa karekau he data-bs-no-jqueryhuanga kua tohua ki runga <body>. Mena ka kitea te jQuery, ka tukuna e Bootstrap nga kaupapa na te punaha takahanga a jQuery. Na, ki te hiahia koe ki te whakarongo ki nga kaupapa a Bootstrap, me whakamahi koe i nga tikanga jQuery ( .on, .one) hei utu mo addEventListener.

$('#myTab a').on('shown.bs.tab', () => {
  // do something...
})

Kua monokia te JavaScript

Ko nga monomai a Bootstrap karekau he takahuri motuhake ina monokia a JavaScript. Mena kei te whakaaro koe ki te wheako o te kaiwhakamahi i tenei keehi, whakamahia <noscript>ki te whakamarama i te ahuatanga (me pehea te whakahohe ano i te JavaScript) ki o kaiwhakamahi, me te taapiri i a koe ake ritenga takahuri.