Skip to main content Skip ad navigationem soUicitudo
Check

Utere Bootstrap's JavaScript modalis plugin ad addere dialogs ad locum tuum pro lightboxes, notificationes usuario, vel omnino contenta consuetudine.

Quomodo facitur

Priusquam incepit cum Bootstrap modulatione modali, scito sequentia legere, sicut nostrae tabulae optiones nuper mutatae sunt.

  • Modales aedificantur cum HTML, CSS, et JavaScript. Super omnia alia in scriptione positi sunt et librum removent <body>ut potius cartis modalibus contentorum.
  • Clicking in modalis "backdrop" automatice claudet modalem.
  • Bootstrap tantum sustinet unam fenestram modalem ad tempus. Modales nidificati non sustinentur ut credamus eas experientias usoris pauperes esse.
  • Modalis usus position: fixed, qui aliquantulum de suo reddendo esse interdum potest. Quotiens fieri potest, pone modalem HTML in summo gradu, ne potentiale impedimentum ab aliis elementis fiat. Verisimile erit exitus incurrere cum .modalintra aliud fixum elementum nidificans.
  • Iterum, propter position: fixedaliquas cautiones cum modalibus in mobilibus machinis utendo. Vide navigatrum subsidium soUicitudo pro details.
  • Ob quam HTML5 sua semantica definit, attributio autofocusHTML effectum in modalibus Bootstrap non habet. Ad eundem effectum assequendum, utere aliqua consuetudine JavaScript:
const myModal = document.getElementById('myModal')
const myInput = document.getElementById('myInput')

myModal.addEventListener('shown.bs.modal', () => {
  myInput.focus()
})
Effectus animationis huius componentis dependet ex prefers-reduced-motioninterrogatione instrumentorum. Videre motum sectionem accessibilitatis nostrae documentationis reductam .

Demos legere et usus guidelines serva.

Exempla

Infra exemplum modalis staticposition (est eius significatio et displayvexata). Inclusa sunt caput modalis, corpus modale (requiritur ad padding) et footer modalis (libitum). Rogamus ut includas capitis modales actiones dimissionis quoties fieri potest, vel aliam explicitam dimissionem praebere.

<div class="modal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>Modal body text goes here.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
In superiore exemplo stabili utimur <h5>ad vitandas quaestiones cum Hierarchia in pagina documentorum. Structure autem dialogus modalis suum singulare documentum/contextum repraesentat, ita .modal-titlespecimen esse debet <h1>. Si opus est, font magnitudine utilitates uti potes speciem capitis temperare. Accedunt exempla omnia quae sequuntur.

Vivamus demo

Toggle operantes demo modalem pyga infra strepitando. A summo paginae labatur et deficiet.

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Static backdrop

Cum backdrops ad static destinatur, modalis non claudet cum extra illud strepitando. Infra ipsum preme experior.

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
  Launch static backdrop modal
</button>

<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Understood</button>
      </div>
    </div>
  </div>
</div>

Scrolling diu contentus

Cum modales nimis longiores fiunt ad prospectum seu machinam usoris, ipsi paginae ipsius independentes sunt. Conare demo inferius videre quid velis.

.modal-dialog-scrollablePotes etiam facere librum modalem modalem qui librum corporis modalis admittit addendo .modal-dialog.

<!-- Scrollable modal -->
<div class="modal-dialog modal-dialog-scrollable">
  ...
</div>

Vertically sitas

Adde .modal-dialog-centeredad .modal-dialogverticaliter centrum modalem.

<!-- Vertically centered modal -->
<div class="modal-dialog modal-dialog-centered">
  ...
</div>

<!-- Vertically centered scrollable modal -->
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
  ...
</div>

Instrumentorum et popovers

Instrumenta et popoveri intra modales prout opus est poni possunt. Cum modalia clausa sint, instrumenta quaevis instrumenta et popoveri intus ipso facto dimittuntur.

<div class="modal-body">
  <h2 class="fs-5">Popover in a modal</h2>
  <p>This <a href="#" role="button" class="btn btn-secondary" data-bs-toggle="popover" title="Popover title" data-bs-content="Popover body content is set in this attribute.">button</a> triggers a popover on click.</p>
  <hr>
  <h2 class="fs-5">Tooltips in a modal</h2>
  <p><a href="#" data-bs-toggle="tooltip" title="Tooltip">This link</a> and <a href="#" data-bs-toggle="tooltip" title="Tooltip">that link</a> have tooltips on hover.</p>
</div>

Usus malesuada euismod

Utilise Bootstrap ratio gridis in modali .container-fluidintra nidificando .modal-body. Tum utere normali eget systematis classes sicut alibi vis.

<div class="modal-body">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4">.col-md-4</div>
      <div class="col-md-4 ms-auto">.col-md-4 .ms-auto</div>
    </div>
    <div class="row">
      <div class="col-md-3 ms-auto">.col-md-3 .ms-auto</div>
      <div class="col-md-2 ms-auto">.col-md-2 .ms-auto</div>
    </div>
    <div class="row">
      <div class="col-md-6 ms-auto">.col-md-6 .ms-auto</div>
    </div>
    <div class="row">
      <div class="col-sm-9">
        Level 1: .col-sm-9
        <div class="row">
          <div class="col-8 col-sm-6">
            Level 2: .col-8 .col-sm-6
          </div>
          <div class="col-4 col-sm-6">
            Level 2: .col-4 .col-sm-6
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Varius contentus modalis

Habere fasciculum globuli omnes felis eundem modalem cum contentis leviter diversis? Usus event.relatedTargetet HTML data-bs-*attributa variare contenta modalis pendentibus quibus globulus strepebat.

Infra est demo viva exemplum HTML et JavaScript. Pro magis informationes, lege modales eventus docs pro details de relatedTarget.

html
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@mdo">Open modal for @mdo</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@fat">Open modal for @fat</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@getbootstrap">Open modal for @getbootstrap</button>

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalLabel">New message</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form>
          <div class="mb-3">
            <label for="recipient-name" class="col-form-label">Recipient:</label>
            <input type="text" class="form-control" id="recipient-name">
          </div>
          <div class="mb-3">
            <label for="message-text" class="col-form-label">Message:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send message</button>
      </div>
    </div>
  </div>
</div>
const exampleModal = document.getElementById('exampleModal')
exampleModal.addEventListener('show.bs.modal', event => {
  // Button that triggered the modal
  const button = event.relatedTarget
  // Extract info from data-bs-* attributes
  const recipient = button.getAttribute('data-bs-whatever')
  // If necessary, you could initiate an AJAX request here
  // and then do the updating in a callback.
  //
  // Update the modal's content.
  const modalTitle = exampleModal.querySelector('.modal-title')
  const modalBodyInput = exampleModal.querySelector('.modal-body input')

  modalTitle.textContent = `New message to ${recipient}`
  modalBodyInput.value = recipient
})

Toggle inter modales

Toggle inter plures modales cum subtilioribus quibusdam data-bs-targetet data-bs-toggleattributis. Exempli gratia, tesseram rete modalem ab intra iam apertum signum modalis toggle posses. Quaeso nota plura modalia simul aperta esse non possunt — haec methodus simpliciter toggles inter duos modales separatos.

Aperi primum modalis
html
<div class="modal fade" id="exampleModalToggle" aria-hidden="true" aria-labelledby="exampleModalToggleLabel" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalToggleLabel">Modal 1</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Show a second modal and hide this one with the button below.
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" data-bs-target="#exampleModalToggle2" data-bs-toggle="modal">Open second modal</button>
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="exampleModalToggle2" aria-hidden="true" aria-labelledby="exampleModalToggleLabel2" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="exampleModalToggleLabel2">Modal 2</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Hide this modal and show the first with the button below.
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" data-bs-target="#exampleModalToggle" data-bs-toggle="modal">Back to first</button>
      </div>
    </div>
  </div>
</div>
<a class="btn btn-primary" data-bs-toggle="modal" href="#exampleModalToggle" role="button">Open first modal</a>

Mutare animationem

Variabilis $modal-fade-transformstatum transformationem determinat .modal-dialogante modu defluxionis in animatione, $modal-show-transformvariabilis transformationem determinat in .modal-dialogfine modu flexae in animationis.

Si exempli gratia vis zoom-in animante, potes ponere $modal-fade-transform: scale(.8).

Aufer animationem

Modales enim, qui simpliciter apparent potius quam in conspectum decident, .fadegenus e charactere modali removent.

<div class="modal" tabindex="-1" aria-labelledby="..." aria-hidden="true">
  ...
</div>

Dynamic iuga

Si altitudo modalis mutationum cum aperta est, vocare debes myModal.handleUpdate()ad componendum locum modalis in casu scrollbar quod apparet.

Accessibility

Adde scito aria-labelledby="...", referens titulum modalem , ad .modal. Accedit, quod descriptionem dialogi modalis tui cum aria-describedbyon .modal. Nota te non opus addere role="dialog"cum iam per JavaScript.

Embedding YouTube videos

Embedding YouTube videos in modalibus additional JavaScript non requirit in Bootstrap ut automatice playback prohibere et magis. Vide hoc utile Stack superfluum post pro magis notitia.

Moles libitum

Modales tres magnitudinum ad libitum habent, in promptu per modifier classes ponendas .modal-dialog. Hae magnitudines calcitrare in quibusdam confractionibus ad vitandarum schedulae horizontales in prospectibus angustioribus.

Magnitudo Classis Modal max-latitudo
Parvus .modal-sm 300px
Default Nullus 500px
Magna .modal-lg 800px
Extra large .modal-xl 1140px

Nostrum defaltum modalis sine determinatione classis constituit magnitudinem modalem "medii".

<div class="modal-dialog modal-xl">...</div>
<div class="modal-dialog modal-lg">...</div>
<div class="modal-dialog modal-sm">...</div>

Modal Fullscreen

Alius dominandi modus est option pop sursum modalis quae conspectum usoris tegit, praesto per classes determinatas quae in a ponuntur .modal-dialog.

Classis Availability
.modal-fullscreen Semper
.modal-fullscreen-sm-down 576px
.modal-fullscreen-md-down 768px
.modal-fullscreen-lg-down 992px
.modal-fullscreen-xl-down 1200px
.modal-fullscreen-xxl-down 1400px
<!-- Full screen modal -->
<div class="modal-dialog modal-fullscreen-sm-down">
  ...
</div>

CSS

Variabilium

Additur in v5.2.0

Cum pars Bootstrap evolutae CSS variabiles accedunt, modales nunc CSS variabilium localium utuntur in .modalet .modal-backdroppro aucta real-time css. Valores variabilium pro CSS per Sass positae sunt, ergo etiam adhuc Sass customization adiuvatur.

  --#{$prefix}modal-zindex: #{$zindex-modal};
  --#{$prefix}modal-width: #{$modal-md};
  --#{$prefix}modal-padding: #{$modal-inner-padding};
  --#{$prefix}modal-margin: #{$modal-dialog-margin};
  --#{$prefix}modal-color: #{$modal-content-color};
  --#{$prefix}modal-bg: #{$modal-content-bg};
  --#{$prefix}modal-border-color: #{$modal-content-border-color};
  --#{$prefix}modal-border-width: #{$modal-content-border-width};
  --#{$prefix}modal-border-radius: #{$modal-content-border-radius};
  --#{$prefix}modal-box-shadow: #{$modal-content-box-shadow-xs};
  --#{$prefix}modal-inner-border-radius: #{$modal-content-inner-border-radius};
  --#{$prefix}modal-header-padding-x: #{$modal-header-padding-x};
  --#{$prefix}modal-header-padding-y: #{$modal-header-padding-y};
  --#{$prefix}modal-header-padding: #{$modal-header-padding}; // Todo in v6: Split this padding into x and y
  --#{$prefix}modal-header-border-color: #{$modal-header-border-color};
  --#{$prefix}modal-header-border-width: #{$modal-header-border-width};
  --#{$prefix}modal-title-line-height: #{$modal-title-line-height};
  --#{$prefix}modal-footer-gap: #{$modal-footer-margin-between};
  --#{$prefix}modal-footer-bg: #{$modal-footer-bg};
  --#{$prefix}modal-footer-border-color: #{$modal-footer-border-color};
  --#{$prefix}modal-footer-border-width: #{$modal-footer-border-width};
  
  --#{$prefix}backdrop-zindex: #{$zindex-modal-backdrop};
  --#{$prefix}backdrop-bg: #{$modal-backdrop-bg};
  --#{$prefix}backdrop-opacity: #{$modal-backdrop-opacity};
  

Sass variables

$modal-inner-padding:               $spacer;

$modal-footer-margin-between:       .5rem;

$modal-dialog-margin:               .5rem;
$modal-dialog-margin-y-sm-up:       1.75rem;

$modal-title-line-height:           $line-height-base;

$modal-content-color:               null;
$modal-content-bg:                  $white;
$modal-content-border-color:        var(--#{$prefix}border-color-translucent);
$modal-content-border-width:        $border-width;
$modal-content-border-radius:       $border-radius-lg;
$modal-content-inner-border-radius: subtract($modal-content-border-radius, $modal-content-border-width);
$modal-content-box-shadow-xs:       $box-shadow-sm;
$modal-content-box-shadow-sm-up:    $box-shadow;

$modal-backdrop-bg:                 $black;
$modal-backdrop-opacity:            .5;

$modal-header-border-color:         var(--#{$prefix}border-color);
$modal-header-border-width:         $modal-content-border-width;
$modal-header-padding-y:            $modal-inner-padding;
$modal-header-padding-x:            $modal-inner-padding;
$modal-header-padding:              $modal-header-padding-y $modal-header-padding-x; // Keep this for backwards compatibility

$modal-footer-bg:                   null;
$modal-footer-border-color:         $modal-header-border-color;
$modal-footer-border-width:         $modal-header-border-width;

$modal-sm:                          300px;
$modal-md:                          500px;
$modal-lg:                          800px;
$modal-xl:                          1140px;

$modal-fade-transform:              translate(0, -50px);
$modal-show-transform:              none;
$modal-transition:                  transform .3s ease-out;
$modal-scale-transform:             scale(1.02);

Loop

Responsivum modales fullscreen generantur per $breakpointsmap et loop in scss/_modal.scss.

@each $breakpoint in map-keys($grid-breakpoints) {
  $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
  $postfix: if($infix != "", $infix + "-down", "");

  @include media-breakpoint-down($breakpoint) {
    .modal-fullscreen#{$postfix} {
      width: 100vw;
      max-width: none;
      height: 100%;
      margin: 0;

      .modal-content {
        height: 100%;
        border: 0;
        @include border-radius(0);
      }

      .modal-header,
      .modal-footer {
        @include border-radius(0);
      }

      .modal-body {
        overflow-y: auto;
      }
    }
  }
}

Consuetudinem

Plugin modalis toggles tuas absconditas in demanda, per data attributa vel JavaScript. Etiam mores defaltam scrolling vincit et generat .modal-backdroput cliccam aream praebeat ad dimittendum modales ostensos cum extra modales clicking.

Via data attributa

Toggle

Modalis eu sine scripto JavaScript. Pone data-bs-toggle="modal"in elementum moderatoris, ut puga pyga, una cum a data-bs-target="#foo"vel href="#foo"ut scopum modalem specificum toggle.

<button type="button" data-bs-toggle="modal" data-bs-target="#myModal">Launch modal</button>

Dimitte

Dimissio fieri potest cum dataattributo in pyga intra modalem ut infra demonstratum est:

<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

aut in puga extra modalem utens, data-bs-targetut infra demonstratum est;

<button type="button" class="btn-close" data-bs-dismiss="modal" data-bs-target="#my-modal" aria-label="Close"></button>
Dum uterque modus ad dimittendum modalem sustentatur, mementote extra dimittendum modalem non aequare ARIA Authoring Practices Guide dialogum (modalis) exemplar . Hoc fac cum periculo tuo.

Via JavaScript

Facere modalis cum una JavaScript:

const myModal = new bootstrap.Modal(document.getElementById('myModal'), options)
// or
const myModalAlternative = new bootstrap.Modal('#myModal', options)

Optiones

Cum optiones transeantur per data attributa vel JavaScript, potes appendere nomen optionis data-bs-, ut in data-bs-animation="{value}". Fac mutare casus genus optionis nominis ab " camelCase " ad " kebab-casum " cum transeundo optiones per data attributa. Exempli gratia data-bs-custom-class="beautifier"loco data-bs-customClass="beautifier".

Sicut de Bootstrap 5.2.0, omnia membra experimentalem datam reservatam sustinent data-bs-configquae figuram simplicem componentem sicut chorda JSON domum habere potest. Cum elementum habet data-bs-config='{"delay":0, "title":123}'et data-bs-title="456"attributa, valor finalis titleerit 456et attributa separata data valores supra datos vincent data-bs-config. Praeterea exsistentes notitiae attributae possunt domum JSON valores similes data-bs-delay='{"show":0,"hide":150}'.

Nomen Type Default Descriptio
backdrop Boolean,'static' true Includes elementum modal-backdrop. Vel, specificare staticrecessum qui non claudit modalem cum strepitando.
focus Boolean true Focum ponit in modali cum initialized.
keyboard Boolean true Modalis claudit cum clavis effugium premitur.

Methodi

Modi asynchronous et transitus

Omnes API modi asynchroni sunt et transitus committitur . Redeunt ad RECENS mox ut transitus incipiat sed antequam finiatur . Methodus praeterea in transitus transeuntis ignorabitur .

See our JavaScript documentation for more information .

Transeuntes optiones

Exagitat tuam contentus modalem. Acceptat optiones libitum object.

const myModal = new bootstrap.Modal('#myModal', {
  keyboard: false
})
Methodus Descriptio
dispose Modalis elementum destruit. (Recondita removet data in dom elementum)
getInstance Ratio static, quae te permittit ut instantia modalis cum elemento DOM coniungitur.
getOrCreateInstance Statica methodus, quae te permittit ut instantia modalis cum elemento DOM coniungitur, vel novum crea in casu non initialized erat.
handleUpdate Manually statum modalis legitimum, si altitudo modalis mutationum dum aperta est (ie in casu scrollbar apparet).
hide Manually celat modalis. Redit ad RECENS antequam modalis actu absconditus est (id antequam hidden.bs.modalevenit).
show Manually modal opens. RECENS REcurrit antequam modalis actu ostensum est (id antequam shown.bs.modalevenit). Item, elementum dom transire potes ut argumentum quod recipi potest in eventibus modalibus (sicut relatedTargetproprietas). ( ie const modalToggle = document.getElementById('toggleMyModal'); myModal.show(modalToggle).
toggle Manually toggles modalis. Redit ad RECENS antequam modalis actu ostensum est vel absconditum (id est ante shown.bs.modalvel hidden.bs.modaleventum).

Events

Classis modalis Bootstrap paucas eventus exponit pro hamo in functionem modalem. Omnes eventus modales accenduntur ad ipsum modalem (id est ad <div class="modal">).

Eventus Descriptio
hide.bs.modal Hic eventus statim accensus est, cum hidemethodus instantia vocata est.
hidden.bs.modal Eventus hic accensus est cum modalis occultationem ab usore confecit (exspectabit CSS transitus ad perficiendum).
hidePrevented.bs.modal Hic eventus accenditur cum modalis ostenditur, eius backstilla est staticet strepita extra modalem exercetur. Eventus etiam accensus est cum clavis effugium premitur et keyboardoptio datur false.
show.bs.modal Huius rei accendit statim cum showinstantia methodus appellatur. Si causatur per strepita, elementum clicked praesto est ut relatedTargetproprietas eventus.
shown.bs.modal Eventus hic accensus est cum modalis utenti visibilia facta est (exspectabit CSS transitus ad perficiendum). Si causatur per strepita, elementum clicked praesto est ut relatedTargetproprietas eventus.
const myModalEl = document.getElementById('myModal')
myModalEl.addEventListener('hidden.bs.modal', event => {
  // do something...
})