Rekọja si akoonu akọkọ Rekọja si lilọ kiri awọn docs
Check
in English

JavaScript

Mu Bootstrap wa si igbesi aye pẹlu awọn afikun JavaScript iyan wa. Kọ ẹkọ nipa itanna kọọkan, data wa ati awọn aṣayan API ti eto, ati diẹ sii.

Olukuluku tabi akopọ

Awọn afikun le wa ni ẹyọkan (lilo Bootstrap's olukuluku js/dist/*.js), tabi gbogbo wọn ni ẹẹkan lilo bootstrap.jstabi miniified bootstrap.min.js(ko pẹlu mejeeji).

Ti o ba lo lapapo kan (Pack Web, Parcel, Vite…), o le lo /js/dist/*.jsawọn faili ti o ti ṣetan UMD.

Lilo pẹlu JavaScript ilana

Lakoko ti Bootstrap CSS le ṣee lo pẹlu eyikeyi ilana, Bootstrap JavaScript ko ni ibamu ni kikun pẹlu awọn ilana JavaScript bii React, Vue, ati Angular eyiti o gba oye kikun ti DOM. Mejeeji Bootstrap ati ilana naa le gbiyanju lati yi ẹya DOM kanna pada, ti o mu abajade awọn idun bii awọn silẹ ti o di ni ipo “ṣii”.

Yiyan ti o dara julọ fun awọn ti nlo iru awọn ilana ni lati lo idii-pato kan pato dipo Bootstrap JavaScript. Eyi ni diẹ ninu awọn aṣayan olokiki julọ:

Lilo Bootstrap bi module

Gbiyanju o funrararẹ! Ṣe igbasilẹ koodu orisun ati demo iṣẹ fun lilo Bootstrap gẹgẹbi module ES lati ibi ipamọ twbs/awọn apẹẹrẹ . O tun le ṣii apẹẹrẹ ni StackBlitz .

A pese ẹya ti Bootstrap ti a ṣe bi ESM( bootstrap.esm.jsati bootstrap.esm.min.js) eyiti o fun ọ laaye lati lo Bootstrap gẹgẹbi module ninu ẹrọ aṣawakiri, ti awọn aṣawakiri rẹ ti o fojusi ṣe atilẹyin rẹ .

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

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

Ti a ṣe afiwe si awọn bundler JS, lilo ESM ni ẹrọ aṣawakiri nilo ki o lo ọna kikun ati orukọ faili dipo orukọ module. Ka diẹ sii nipa awọn modulu JS ni ẹrọ aṣawakiri. Ti o ni idi ti a lo 'bootstrap.esm.min.js'dipo ti 'bootstrap'oke. Sibẹsibẹ, eyi jẹ idiju siwaju sii nipasẹ igbẹkẹle Popper wa, eyiti o gbe agbewọle Popper sinu JavaScript wa bii bẹ:

import * as Popper from "@popperjs/core"

Ti o ba gbiyanju eyi bi o ṣe jẹ, iwọ yoo rii aṣiṣe ninu console bii atẹle:

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

Lati ṣatunṣe eyi, o le lo ohun importmaplati yanju awọn orukọ module lainidii lati pari awọn ọna. Ti awọn aṣàwákiri ìfọkànsí rẹ ko ba ṣe atilẹyin importmap, iwọ yoo nilo lati lo iṣẹ akanṣe es-module-shims . Eyi ni bii o ṣe n ṣiṣẹ fun Bootstrap ati 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>

Awọn igbẹkẹle

Diẹ ninu awọn afikun ati awọn paati CSS dale lori awọn afikun miiran. Ti o ba pẹlu awọn afikun ni ẹyọkan, rii daju lati ṣayẹwo fun awọn igbẹkẹle wọnyi ninu awọn docs.

Awọn ifilọlẹ wa, popovers, ati awọn imọran irinṣẹ tun dale lori Popper .

Awọn eroja data

O fẹrẹ to gbogbo awọn afikun Bootstrap ni a le mu ṣiṣẹ ati tunto nipasẹ HTML nikan pẹlu awọn abuda data (ọna ti o fẹ wa ti lilo iṣẹ ṣiṣe JavaScript). Rii daju pe o lo eto kan ti awọn abuda data lori ẹyọkan (fun apẹẹrẹ, o ko le ṣe okunfa ohun elo irinṣẹ ati modal lati bọtini kanna.)

Bi awọn aṣayan ṣe le kọja nipasẹ awọn abuda data tabi JavaScript, o le fi orukọ aṣayan si data-bs-, bi ninu data-bs-animation="{value}". Rii daju lati yi iru ọran ti orukọ aṣayan pada lati “ CamelCase ” si “ kebab-case ” nigba gbigbe awọn aṣayan nipasẹ awọn abuda data. Fun apẹẹrẹ, lo data-bs-custom-class="beautifier"dipo data-bs-customClass="beautifier".

Bi ti Bootstrap 5.2.0, gbogbo awọn paati ṣe atilẹyin abuda data ipamọ idanwodata-bs-config ti o le ṣe atunto paati ti o rọrun bi okun JSON kan. Nigbati ohun kan ba ni data-bs-config='{"delay":0, "title":123}'ati data-bs-title="456"awọn abuda, iye ikẹhin titleyoo jẹ 456ati awọn abuda data lọtọ yoo dojuti awọn iye ti a fun lori data-bs-config. Ni afikun, awọn abuda data ti o wa ni anfani lati gbe awọn iye JSON bii data-bs-delay='{"show":0,"hide":150}'.

Awọn yiyan

A lo abinibi querySelectorati querySelectorAllawọn ọna lati beere awọn eroja DOM fun awọn idi iṣẹ, nitorinaa o gbọdọ lo awọn yiyan to wulo . Ti o ba lo awọn yiyan pataki bi collapse:Example, rii daju pe o sa fun wọn.

Awọn iṣẹlẹ

Bootstrap n pese awọn iṣẹlẹ aṣa fun ọpọlọpọ awọn iṣe alailẹgbẹ awọn afikun. Ni gbogbogbo, iwọnyi wa ni fọọmu ailopin ati ti o ti kọja - nibiti ailopin (fun apẹẹrẹ show) ti jẹ okunfa ni ibẹrẹ iṣẹlẹ kan, ati fọọmu apakan apakan ti o kọja (fun apẹẹrẹ shown) jẹ okunfa lori ipari iṣẹ kan.

Gbogbo awọn iṣẹlẹ ailopin pese preventDefault()iṣẹ ṣiṣe. Eyi n pese agbara lati da ipaniyan ti iṣe ṣaaju ki o to bẹrẹ. Pada eke pada lati ọdọ oluṣakoso iṣẹlẹ yoo tun pe laifọwọyi preventDefault().

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

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

API ètò

Gbogbo awọn olupilẹṣẹ gba ohun awọn aṣayan iyan tabi nkankan (eyiti o bẹrẹ ohun itanna kan pẹlu ihuwasi aiyipada):

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

Ti o ba fẹ lati gba apẹẹrẹ itanna kan pato, ohun itanna kọọkan ṣafihan getInstanceọna kan. Fun apẹẹrẹ, lati mu apẹẹrẹ pada taara lati ẹya:

bootstrap.Popover.getInstance(myPopoverEl)

Ọna yii yoo pada nullti apẹẹrẹ ko ba bẹrẹ lori nkan ti o beere.

Ni omiiran, getOrCreateInstancele ṣee lo lati gba apẹẹrẹ ti o ni nkan ṣe pẹlu nkan DOM kan, tabi ṣẹda tuntun kan ti ko ba ṣe ipilẹṣẹ.

bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)

Ni ọran ti apẹẹrẹ ko ba ṣe ipilẹṣẹ, o le gba ati lo ohun atunto yiyan bi ariyanjiyan keji.

CSS selectors ni constructors

Ni afikun si getInstanceati awọn getOrCreateInstanceọna, gbogbo awọn olupilẹṣẹ ohun itanna le gba nkan DOM kan tabi yiyan CSS to wulo bi ariyanjiyan akọkọ. Awọn eroja itanna ni a rii pẹlu querySelectorọna nitori awọn afikun wa nikan ṣe atilẹyin ipin kan.

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

Awọn iṣẹ asynchronous ati awọn iyipada

Gbogbo awọn ọna API ti eto jẹ asynchronous ati pada si olupe ni kete ti iyipada ti bẹrẹ, ṣugbọn ṣaaju ki o to pari . Lati le ṣe iṣe ni kete ti iyipada ba ti pari, o le tẹtisi iṣẹlẹ ti o baamu.

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

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

Ni afikun, ipe ọna kan lori paati iyipada yoo jẹ kọbikita .

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ọna

Lakoko ti o le dabi pe o tọ lati lo disposeọna lẹsẹkẹsẹ lẹhin hide(), yoo ja si awọn abajade ti ko tọ. Eyi ni apẹẹrẹ ti iṣoro lilo:

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

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

Awọn eto aiyipada

O le yi awọn eto aiyipada pada fun ohun itanna kan nipa yiyipada ohun itanna Constructor.Defaultnaa:

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

Awọn ọna ati awọn ohun-ini

Gbogbo ohun itanna Bootstrap ṣafihan awọn ọna atẹle ati awọn ohun-ini aimi.

Ọna Apejuwe
dispose Pa ohun ano ká modal. (Yọ data ti o fipamọ sori nkan DOM kuro)
getInstance Ọna aimi eyiti o fun ọ laaye lati gba apẹẹrẹ modal ti o ni nkan ṣe pẹlu nkan DOM kan.
getOrCreateInstance Ọna aimi eyiti o fun ọ laaye lati gba apẹẹrẹ modal ti o ni nkan ṣe pẹlu nkan DOM kan, tabi ṣẹda ọkan tuntun ni ọran ti ko ṣe ipilẹṣẹ.
Aimi ohun ini Apejuwe
NAME Da orukọ itanna pada. (Apeere bootstrap.Tooltip.NAME:)
VERSION Ẹya ti ọkọọkan ti awọn afikun Bootstrap ni o le wọle nipasẹ VERSIONohun-ini ti olupilẹṣẹ ohun itanna (Apẹẹrẹ bootstrap.Tooltip.VERSION:)

Sanitizer

Awọn imọran irinṣẹ ati Awọn agbejade lo imototo ti a ṣe sinu rẹ lati sọ awọn aṣayan di mimọ ti o gba HTML.

Iye aiyipada allowListni atẹle yii:

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

Ti o ba fẹ ṣafikun awọn iye tuntun si aiyipada yii allowListo le ṣe atẹle naa:

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)

Ti o ba fẹ lati fori imototo wa nitori pe o fẹ lati lo ile-ikawe iyasọtọ, fun apẹẹrẹ DOMPurify , o yẹ ki o ṣe atẹle naa:

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

Ni yiyan lilo jQuery

Iwọ ko nilo jQuery ni Bootstrap 5 , ṣugbọn o tun ṣee ṣe lati lo awọn paati wa pẹlu jQuery. Ti Bootstrap ba ṣe awari jQueryninu windownkan naa, yoo ṣafikun gbogbo awọn paati wa ni eto itanna jQuery. Eyi n gba ọ laaye lati ṣe awọn atẹle:

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

Kanna n lọ fun wa miiran irinše.

Ko si ija

Nigba miiran o jẹ dandan lati lo awọn afikun Bootstrap pẹlu awọn ilana UI miiran. Ni awọn ipo wọnyi, awọn ikọlu aaye orukọ le waye lẹẹkọọkan. Ti eyi ba ṣẹlẹ, o le pe .noConflictohun itanna ti o fẹ lati yi iye pada.

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

Bootstrap ko ṣe atilẹyin fun awọn ile-ikawe JavaScript ẹni-kẹta gẹgẹbi Afọwọṣe tabi jQuery UI. Laibikita .noConflictati awọn iṣẹlẹ ti a fun lorukọ, awọn iṣoro ibamu le wa ti o nilo lati ṣatunṣe funrararẹ.

jQuery iṣẹlẹ

Bootstrap yoo ṣe awari jQuery ti o ba jQuerywa ninu windowohun naa ko si si data-bs-no-jqueryẹda ti o ṣeto lori <body>. Ti a ba rii jQuery, Bootstrap yoo gbejade awọn iṣẹlẹ ọpẹ si eto iṣẹlẹ jQuery. Nitorina ti o ba fẹ tẹtisi awọn iṣẹlẹ Bootstrap, iwọ yoo ni lati lo awọn ọna jQuery ( .on, .one) dipo addEventListener.

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

JavaScript alaabo

Awọn afikun Bootstrap ko ni ipadasẹhin pataki nigbati JavaScript jẹ alaabo. Ti o ba bikita nipa iriri olumulo ninu ọran yii, lo <noscript>lati ṣalaye ipo naa (ati bi o ṣe le tun JavaScript ṣiṣẹ) si awọn olumulo rẹ, ati/tabi ṣafikun awọn isubu aṣa tirẹ.