Tlolela ho litaba tsa mantlha Tlolela ho li-docs navigation
Check
in English

JavaScript

Etsa hore Bootstrap e phele ka li-plugins tsa rona tsa boikhethelo tsa JavaScript. Ithute ka plugin ka 'ngoe, likhetho tsa rona tsa data le mananeo a API, le tse ling.

Motho ka mong kapa a kopantswe

Li-plugins li ka kenyeletsoa ka bonngoe (ho sebelisa Bootstrap ka bomong js/dist/*.js), kapa kaofela ka nako e le 'ngoe li sebelisa bootstrap.jskapa tse entsoeng bootstrap.min.js(o se kenyelletse ka bobeli).

Haeba u sebelisa bundler (Webpack, Parcel, Vite…), u ka sebelisa /js/dist/*.jslifaele tse seng li loketse UMD.

Tšebeliso e nang le meralo ea JavaScript

Leha Bootstrap CSS e ka sebelisoa le moralo ofe kapa ofe, Bootstrap JavaScript ha e tsamaellane ka botlalo le meralo ea JavaScript joalo ka React, Vue, le Angular tse nkang tsebo e felletseng ea DOM. Ka bobeli Bootstrap le moralo li ka leka ho fetola ntho e tšoanang ea DOM, e leng se bakang likokoana-hloko tse kang li-dropdown tse lutseng sebakeng se "butsoeng".

Mokhoa o mong o betere bakeng sa ba sebelisang mofuta ona oa meralo ke ho sebelisa sephutheloana se ikhethileng ho fapana le Bootstrap JavaScript. Mona ke tse ling tsa likhetho tse tsebahalang haholo:

Ho sebelisa Bootstrap joalo ka mojule

E leke ka bouena! Khoasolla khoutu ea mohloli le demo ea ho sebetsa bakeng sa ho sebelisa Bootstrap joalo ka mojule oa ES ho tsoa polokelong ea twbs/mehlala . U ka boela ua bula mohlala ho StackBlitz .

Re fana ka mofuta oa Bootstrap o hahiloeng e le ESM( bootstrap.esm.jsle bootstrap.esm.min.js) o u lumellang ho sebelisa Bootstrap joalo ka mojule ho sebatli, haeba libatli tseo u li shebileng li e tšehetsa .

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

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

Ha ho bapisoa le li-bundlers tsa JS, ho sebelisa ESM ho sebatli ho hloka hore u sebelise tsela e felletseng le lebitso la faele ho fapana le lebitso la mojule. Bala haholoanyane ka li-module tsa JS ho sebatli. Ke kahoo re sebelisang 'bootstrap.esm.min.js'sebakeng sa 'bootstrap'holimo. Leha ho le joalo, sena se thatafatsoa ke ho itšetleha ha rona ka Popper, e kenyang Popper ho JavaScript ea rona joalo ka:

import * as Popper from "@popperjs/core"

Haeba u leka sena, u tla bona phoso ho console e kang e latelang:

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

Ho lokisa sena, o ka sebelisa importmapho rarolla mabitso a mojule a sa reroang ho tlatsa litsela. Haeba libatli tseo u li lebileng li sa u tšehetse importmap, u tla hloka ho sebelisa projeke ea es-module-shims . Mona ke kamoo e sebetsang bakeng sa Bootstrap le 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>

Ho itšetleha

Li-plugins tse ling le likarolo tsa CSS li itšetlehile ka li-plugins tse ling. Haeba u kenyelletsa li-plugins ka bonngoe, etsa bonnete ba hore u hlahloba litšepiso tsena ho litokomane.

Li-dropdown tsa rona, li-popover, le lisebelisoa tsa lisebelisoa li boetse li itšetlehile ka Popper .

Litšobotsi tsa data

Hoo e ka bang li-plugins tsohle tsa Bootstrap li ka nolofalloa le ho hlophisoa ka HTML feela ka lintlha tsa data (mokhoa oo re o ratang oa ho sebelisa ts'ebetso ea JavaScript). Etsa bonnete ba hore o sebelisa feela sete e le 'ngoe ea litšobotsi tsa data nthong e le' ngoe (mohlala, u ke ke ua qala sesebelisoa le modal ho tsoa konopo e le 'ngoe.)

Kaha likhetho li ka fetisoa ka lintlha tsa data kapa JavaScript, u ​​ka kenyelletsa lebitso la khetho ho data-bs-, joalo ka data-bs-animation="{value}". Etsa bonnete ba hore o fetola mofuta oa nyeoe ea lebitso la khetho ho tloha " camelCase "ho " kebab-case " ha o fetisa likhetho ka litšobotsi tsa data. Ka mohlala, sebelisa data-bs-custom-class="beautifier"ho e-na le data-bs-customClass="beautifier".

Ho tloha ka Bootstrap 5.2.0, likarolo tsohle li ts'ehetsa tlhahlobo ea data e bolokiloeng data-bs-confige ka bolokang tlhophiso e bonolo ea karolo joalo ka khoele ea JSON. Ha element e na data-bs-config='{"delay":0, "title":123}'le data-bs-title="456"litšoaneleho, boleng ba ho qetela titlebo tla ba 456'me lintlha tse arohaneng tsa data li tla feta boleng bo fanoeng ho data-bs-config. Ntle le moo, litšoaneleho tse teng tsa data li khona ho boloka boleng ba JSON joalo ka data-bs-delay='{"show":0,"hide":150}'.

Bakhethi

Re sebelisa matsoalloa querySelectorle querySelectorAllmekhoa ho botsa likarolo tsa DOM ka mabaka a ts'ebetso, kahoo o tlameha ho sebelisa likhetho tse nepahetseng . Haeba u sebelisa likhetho tse khethehileng joalo collapse:Exampleka , etsa bonnete ba hore u li baleha.

Liketsahalo

Bootstrap e fana ka liketsahalo tsa tloaelo bakeng sa liketso tse ikhethang tsa li-plugins. Ka kakaretso, tsena li tla ka mokhoa o sa feleng le oa nako e fetileng - moo lentsoe le sa feleng (mohlala. show) le qalisoang qalong ea ketsahalo, 'me sebopeho sa eona sa nako e fetileng sa karolo (mohlala. shown) se hlahisoa ha ketso e phethoa.

Liketsahalo tsohle tse sa feleng li fana ka preventDefault()ts'ebetso. Sena se fana ka bokhoni ba ho emisa ts'ebetso ea ketso pele e qala. Ho khutlisa leshano ho tsoa ho mohlokomeli oa liketsahalo ho tla letsetsa hape ka bohona preventDefault().

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

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

Programmatic API

Bahahi bohle ba amohela ntho ea boikhethelo kapa letho (e qalang plugin ka boitšoaro ba eona ba kamehla):

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

Haeba u ka rata ho fumana mohlala o itseng oa plugin, plugin ka 'ngoe e hlahisa getInstancemokhoa. Mohlala, ho khutlisa mohlala ka kotloloho ho tsoa ho element:

bootstrap.Popover.getInstance(myPopoverEl)

Mokhoa ona o tla khutla nullhaeba mohlala o sa qalisoa holim'a ntho e batiloeng.

Ntle le moo, getOrCreateInstancee ka sebelisoa ho etsa hore mohlala o amahane le ntho ea DOM, kapa oa theha e ncha haeba e sa qalisoa.

bootstrap.Popover.getOrCreateInstance(myPopoverEl, configObject)

Haeba ketsahalo e sa qalisoa, e ka amohela le ho sebelisa ntho eo u ka e khethang e le khang ea bobeli.

Bakhethoa ba CSS ho bahahi

Ntle le mekhoa getInstancele getOrCreateInstancemekhoa, baetsi bohle ba li-plugin ba ka amohela karolo ea DOM kapa khetho e nepahetseng ea CSS joalo ka khang ea pele. Lisebelisoa tsa plugin li fumaneha ka querySelectormokhoa ona kaha li-plugins tsa rona li tšehetsa ntho e le 'ngoe feela.

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

Mesebetsi ea Asynchronous le liphetoho

Mekhoa eohle ea lenaneo la API ha e lumellane 'me e khutlela ho motho ea letsetsang hang ha phetoho e qala, empa pele e fela . E le hore u phethe ketso hang ha phetoho e felile, u ka mamela ketsahalo e tsamaisanang le eona.

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

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

Ho feta moo, mohala oa mokhoa ho karolo ea phetoho o tla hlokomolohuoa .

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

disposemokhoa

Le hoja ho ka bonahala ho nepahetse ho sebelisa disposemokhoa hang ka mor'a moo hide(), ho tla lebisa liphellong tse fosahetseng. Mona ke mohlala oa bothata ba tšebeliso:

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

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

Litlhophiso tsa kamehla

U ka fetola litlhophiso tsa kamehla tsa plugin ka ho fetola Constructor.Defaultntho ea plugin:

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

Mekhoa le thepa

Plugin e 'ngoe le e' ngoe ea Bootstrap e pepesa mekhoa e latelang le thepa e tsitsitseng.

Mokhoa Tlhaloso
dispose E senya modal oa element. (E tlosa lintlha tse bolokiloeng karolong ea DOM)
getInstance Mokhoa o tsitsitseng o u lumellang ho fumana mohlala oa modal o amanang le ntho ea DOM.
getOrCreateInstance Mokhoa o tsitsitseng o o lumellang ho fumana mohlala oa modal o amanang le element ea DOM, kapa u thehe e ncha haeba e sa qalisoa.
Thepa e tsitsitseng Tlhaloso
NAME E khutlisa lebitso la plugin. (Mohlala bootstrap.Tooltip.NAME:)
VERSION Mofuta oa e 'ngoe le e' ngoe ea li-plugins tsa Bootstrap e ka fumaneha ka VERSIONthepa ea sehahi sa plugin (Mohlala bootstrap.Tooltip.VERSION:)

Sanitizer

Lisebelisoa le li-Popovers li sebelisa sanitizer ea rona e hahelletsoeng ka hare ho hloekisa likhetho tse amohelang HTML.

Boleng ba kamehla allowListke bo latelang:

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

Haeba u batla ho eketsa boleng bo bocha sebakeng sena sa kamehla allowListu ka etsa tse latelang:

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)

Haeba u batla ho qoba sanitizer ea rona hobane u khetha ho sebelisa laeborari e inehetseng, mohlala DOMpurify , u lokela ho etsa se latelang:

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

Ka boikhethelo sebelisa jQuery

Ha u hloke jQuery ho Bootstrap 5 , empa ho ntse ho khoneha ho sebelisa likarolo tsa rona ka jQuery. Haeba Bootstrap e lemoha jQuerynthong window, e tla eketsa likarolo tsohle tsa rona ho jQuery's plugin system. Sena se o lumella ho etsa tse latelang:

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

Ho joalo le ka likarolo tse ling tsa rona.

Ha ho khohlano

Ka linako tse ling hoa hlokahala ho sebelisa li-plugins tsa Bootstrap tse nang le meralo e meng ea UI. Maemong ana, ka linako tse ling ho ka ba le likhohlano tsa sebaka sa mabitso. Haeba sena se etsahala, u ka bitsa .noConflictplugin u lakatsa ho khutlisetsa boleng ba.

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

Bootstrap ha e tšehetse ka molao lilaebrari tsa mokha oa boraro tsa JavaScript joalo ka Prototype kapa jQuery UI. Leha .noConflictho na le liketsahalo tse arohaneng le mabitso, ho kanna ha ba le mathata a ho lumellana ao u hlokang ho a lokisa u le mong.

Liketsahalo tsa jQuery

Bootstrap e tla lemoha jQuery haeba jQuerye le teng ka har'a windowntho 'me ha ho na data-bs-no-jquerytšobotsi e behiloeng ho <body>. Haeba jQuery e fumaneha, Bootstrap e tla hlahisa liketsahalo ka lebaka la sistimi ea liketsahalo ea jQuery. Kahoo haeba u batla ho mamela liketsahalo tsa Bootstrap, u tla tlameha ho sebelisa mekhoa ea jQuery ( .on, .one) sebakeng sa addEventListener.

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

JavaScript e holofalitsoe

Li-plugins tsa Bootstrap ha li na mokhoa o khethehileng oa ho khutla ha JavaScript e koetsoe. Haeba u tsotella boiphihlelo ba mosebelisi ntlheng ena, sebelisa <noscript>ho hlalosa boemo (le mokhoa oa ho lumella JavaScript hape) ho basebelisi ba hau, le/kapa eketsa liphoso tsa hau tsa tloaelo.