Pitani kuzinthu zazikulu Pitani kumayendedwe adocs
Check
in English

JavaScript

Bweretsani Bootstrap kukhala ndi moyo ndi mapulagini athu osankha a JavaScript. Phunzirani za pulogalamu yowonjezera iliyonse, zosankha zathu zamapulogalamu a API, ndi zina zambiri.

Munthu payekha kapena wophatikizidwa

Mapulagini amatha kuphatikizidwa payekhapayekha (pogwiritsa ntchito Bootstrap payekha js/dist/*.js), kapena zonse nthawi imodzi pogwiritsa ntchito bootstrap.jskapena minified bootstrap.min.js(musaphatikizepo zonse ziwiri).

Ngati mugwiritsa ntchito bundler (Webpack, Parcel, Vite…), mutha kugwiritsa ntchito /js/dist/*.jsmafayilo omwe ali okonzeka ku UMD.

Kugwiritsa ntchito ndi JavaScript frameworks

Ngakhale Bootstrap CSS itha kugwiritsidwa ntchito ndi chimango chilichonse, Bootstrap JavaScript siyigwirizana kwathunthu ndi mawonekedwe a JavaScript monga React, Vue, ndi Angular omwe amadziwa zonse za DOM. Zonse ziwiri za Bootstrap ndi chimango zitha kuyesa kusintha chinthu chomwecho cha DOM, zomwe zimapangitsa kuti pakhale nsikidzi ngati zotsikira zomwe zakhazikika pamalo "otseguka".

Njira ina yabwino kwa iwo omwe amagwiritsa ntchito mitundu iyi ndikugwiritsa ntchito phukusi lachindunji m'malo mwa Bootstrap JavaScript. Nazi zina mwazosankha zodziwika kwambiri:

Kugwiritsa ntchito Bootstrap ngati module

Yesani nokha! Tsitsani kachidindo koyambira ndi chiwonetsero chogwirira ntchito pogwiritsa ntchito Bootstrap ngati gawo la ES kuchokera pankhokwe ya twbs/examples . Mukhozanso kutsegula chitsanzo mu StackBlitz .

Timapereka mtundu wa Bootstrap womangidwa monga ESM( bootstrap.esm.jsndi bootstrap.esm.min.js) womwe umakupatsani mwayi wogwiritsa ntchito Bootstrap ngati gawo mu msakatuli, ngati asakatuli omwe mukufuna amathandizira .

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

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

Poyerekeza ndi ma bundlers a JS, kugwiritsa ntchito ESM mu msakatuli kumafuna kuti mugwiritse ntchito njira yonse ndi dzina la fayilo m'malo mwa dzina la gawo. Werengani zambiri za ma module a JS mu msakatuli. Ndicho chifukwa chake timagwiritsa ntchito 'bootstrap.esm.min.js'm'malo mwa 'bootstrap'pamwamba. Komabe, izi zimakhala zovuta kwambiri chifukwa cha kudalira kwathu kwa Popper, komwe kumalowetsa Popper mu JavaScript yathu motere:

import * as Popper from "@popperjs/core"

Mukayesa izi momwe zilili, muwona cholakwika mu console monga motere:

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

Kuti mukonze izi, mutha kugwiritsa ntchito njira importmapyothetsera ma module osasintha kuti mumalize njira. Ngati asakatuli omwe mukufuna sakugwirizana nawo importmap, muyenera kugwiritsa ntchito pulojekiti ya es-module-shims . Umu ndi momwe zimagwirira ntchito kwa Bootstrap ndi 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>

Zodalira

Mapulagini ena ndi zigawo za CSS zimadalira mapulagini ena. Ngati muphatikiza mapulagini payekhapayekha, onetsetsani kuti mwayang'ana zodalira izi mu ma docs.

Kutsitsa kwathu, popovers, ndi zida zothandizira zimadaliranso Popper .

Makhalidwe a data

Pafupifupi mapulagini onse a Bootstrap amatha kuyatsidwa ndikukonzedwa kudzera mu HTML yokha ndi ma data (njira yomwe timakonda yogwiritsira ntchito JavaScript). Onetsetsani kuti mungogwiritsa ntchito gulu limodzi la data pachinthu chimodzi (mwachitsanzo, simungathe kuyambitsa chida ndi modal kuchokera pa batani lomwelo.)

Monga zosankha zitha kuperekedwa kudzera pa data kapena JavaScript, mutha kuwonjezera dzina lachisankho ku data-bs-, monga data-bs-animation="{value}". Onetsetsani kuti musinthe mtundu wamtundu wa dzina lachisankho kuchokera ku " camelCase " kupita ku " kebab-case " podutsa zosankha pogwiritsa ntchito zizindikiro za data. Mwachitsanzo, gwiritsani ntchito data-bs-custom-class="beautifier"m'malo mwa data-bs-customClass="beautifier".

Kuyambira pa Bootstrap 5.2.0, zigawo zonse zimathandizira chidziwitso chosungidwa cha data data-bs-configchomwe chingathe kukhazikitsa chigawo chosavuta ngati chingwe cha JSON. Chilichonse chikakhala ndi mawonekedwe , mtengo womaliza udzakhala ndipo mawonekedwe osiyana a data adzapitilira zomwe zaperekedwa data-bs-config='{"delay":0, "title":123}'pa . Kuphatikiza apo, zomwe zilipo kale zimatha kusunga ma JSON monga .data-bs-title="456"title456data-bs-configdata-bs-delay='{"show":0,"hide":150}'

Osankha

Timagwiritsa ntchito zakwawo querySelectorkomanso querySelectorAllnjira kufunsa zinthu za DOM pazifukwa zogwirira ntchito, chifukwa chake muyenera kugwiritsa ntchito zosankha zoyenera . Ngati mumagwiritsa ntchito zosankha zapadera monga collapse:Example, onetsetsani kuti mwathawa.

Zochitika

Bootstrap imapereka zochitika zapadera pazochita zapadera za mapulagini ambiri. Nthawi zambiri, izi zimabwera mu mawonekedwe osamalizidwa komanso am'mbuyomu - pomwe mawu osamalitsa (mwachitsanzo. show) amayambika kumayambiriro kwa chochitika, ndipo mawonekedwe ake apitalo (mwachitsanzo. shown) amayambika akamaliza kuchitapo kanthu.

Zochitika zonse zopanda malire zimapereka preventDefault()magwiridwe antchito. Izi zimapereka kuthekera koyimitsa kuchitapo kanthu kusanayambe. Kubweza zabodza kuchokera kwa woyang'anira zochitika kudzayimbanso preventDefault().

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

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

Programmatic API

Omanga onse amavomereza chinthu chosankha kapena ayi (chomwe chimayambitsa pulogalamu yowonjezera ndi machitidwe ake osakhazikika):

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

Ngati mukufuna kupeza pulogalamu yowonjezera, pulogalamu yowonjezera iliyonse imawonetsa getInstancenjira yake. Mwachitsanzo, kuti mutenge chitsanzo kuchokera ku chinthu:

bootstrap.Popover.getInstance(myPopoverEl)

Njirayi ibwereranso nullngati chochitika sichinayambike pa chinthu chomwe mwapemphedwa.

Kapenanso, getOrCreateInstancezitha kugwiritsidwa ntchito kugwirizanitsa ndi chinthu cha DOM, kapena kupanga chatsopano ngati sichinayambike.

bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)

Ngati chochitika sichinayambike, chikhoza kuvomereza ndikugwiritsa ntchito chinthu chosasinthika ngati mtsutso wachiwiri.

CSS selectors mu omanga

Kuphatikiza pa getInstancendi getOrCreateInstancenjira, opanga mapulagini onse amatha kuvomereza chinthu cha DOM kapena chosankha chovomerezeka cha CSS ngati mkangano woyamba. Zinthu zowonjezera zimapezeka ndi querySelectornjira popeza mapulagini athu amangothandizira chinthu chimodzi.

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

Asynchronous ntchito ndi kusintha

Njira zonse zamapulogalamu a API ndizosasinthika ndipo zimabwerera kwa woyimbirayo pomwe kusintha kwayamba, koma kusanathe . Kuti muthe kuchitapo kanthu pakamaliza kusintha, mutha kumvera zomwe zikugwirizana.

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

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

Kuonjezera apo, kuyitana kwa njira pa gawo losintha kudzanyalanyazidwa .

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

disposenjira

Ngakhale zingawoneke ngati zolondola kugwiritsa ntchito disposenjirayo mwamsanga pambuyo pake hide(), zidzabweretsa zotsatira zolakwika. Nachi chitsanzo chakugwiritsa ntchito vuto:

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

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

Zokonda zofikira

Mutha kusintha makonda a pulogalamu yowonjezera posintha chinthu cha pulogalamu yowonjezera Constructor.Default:

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

Njira ndi katundu

Pulagi iliyonse ya Bootstrap imawulula njira zotsatirazi ndi zokhazikika.

Njira Kufotokozera
dispose Imawononga modali ya chinthu. (Imachotsa deta yosungidwa pa chinthu cha DOM)
getInstance Njira yosasunthika yomwe imakupatsani mwayi wopeza modal yolumikizidwa ndi chinthu cha DOM.
getOrCreateInstance Njira yosasunthika yomwe imakupatsani mwayi woti mugwirizane ndi chinthu cha DOM, kapena pangani yatsopano ngati sichinayambike.
Malo osasunthika Kufotokozera
NAME Ikubweza dzina la pulogalamu yowonjezera. (Chitsanzo bootstrap.Tooltip.NAME:)
VERSION Mtundu wa mapulagini aliwonse a Bootstrap atha kupezeka kudzera VERSIONpagulu laopanga pulogalamu yowonjezera (Chitsanzo bootstrap.Tooltip.VERSION:)

Sanitizer

Zida ndi Popovers amagwiritsa ntchito sanitizer yathu yopangira kuti ayeretse zosankha zomwe zimavomereza HTML.

Mtengo allowListwokhazikika ndi uwu:

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

Ngati mukufuna kuwonjezera ma values ​​atsopano pazosintha izi allowListmutha kuchita izi:

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)

Ngati mukufuna kulambalala sanitizer yathu chifukwa mumakonda kugwiritsa ntchito laibulale yodzipereka, mwachitsanzo DOMpurify , muyenera kuchita izi:

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

Mutha kugwiritsa ntchito jQuery

Simukusowa jQuery mu Bootstrap 5 , koma ndizotheka kugwiritsa ntchito zigawo zathu ndi jQuery. Bootstrap ikazindikira jQuerychinthucho window, iwonjezera zida zathu zonse mu pulogalamu yowonjezera ya jQuery. Izi zimakupatsani mwayi wochita izi:

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

Zomwezo zimapitanso ku zigawo zathu zina.

Palibe mkangano

Nthawi zina pamafunika kugwiritsa ntchito mapulagini a Bootstrap okhala ndi ma UI ena. Pazifukwa izi, kugunda kwa mayina kumachitika nthawi zina. Izi zikachitika, mutha kuyitanitsa pulogalamu yowonjezera .noConflictyomwe mukufuna kubwezeretsanso mtengo wake.

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

Bootstrap sichirikiza malaibulale a JavaScript a chipani chachitatu monga Prototype kapena jQuery UI. Ngakhale .noConflictndi zochitika zotchulidwa mayina, pakhoza kukhala zovuta zogwirizana zomwe muyenera kuzikonza nokha.

jQuery zochitika

Bootstrap idzazindikira jQuery ngati jQueryilipo mu windowchinthucho ndipo palibe data-bs-no-jquerychikhalidwe chokhazikitsidwa pa <body>. Ngati jQuery ipezeka, Bootstrap itulutsa zochitika chifukwa cha machitidwe a jQuery. Chifukwa chake ngati mukufuna kumvera zochitika za Bootstrap, muyenera kugwiritsa ntchito njira za jQuery ( .on, .one) m'malo mwa addEventListener.

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

JavaScript yolephereka

Mapulagini a Bootstrap alibe kubweza kwapadera JavaScript ikayimitsidwa. Ngati mumasamala za ogwiritsa ntchito pankhaniyi, gwiritsani ntchito <noscript>kufotokoza momwe zinthu ziliri (ndi momwe mungayambitsirenso JavaScript) kwa ogwiritsa ntchito anu, ndi/kapena onjezani zolakwika zanu.