Luncat ka eusi utama Luncat ka navigasi docs

Anggo plugin modal JavaScript Bootstrap pikeun nambihan dialog kana situs anjeun pikeun kotak lampu, bewara pangguna, atanapi kontén anu lengkep.

Kumaha gawéna

Sateuacan ngamimitian sareng komponén modal Bootstrap, pastikeun maca ieu di handap sabab pilihan ménu kami parantos robih.

  • Modals diwangun ku HTML, CSS, jeung JavaScript. Aranjeunna nuju diposisikan leuwih sagalana sejenna dina dokumen jeung cabut gulung ti <body>ambéh eusi modal scrolls gantina.
  • Ngaklik dina "backdrop" modal bakal otomatis nutup modal.
  • Bootstrap ngan ngarojong hiji jandela modal dina hiji waktu. Modél bersarang henteu didukung sabab kami yakin yén éta mangrupikeun pangalaman pangguna anu goréng.
  • Modals make position: fixed, nu kadang bisa jadi bit husus ngeunaan rendering na. Sabisana, nempatkeun HTML modal anjeun dina posisi tingkat luhur pikeun nyegah poténsi gangguan ti elemen séjén. Anjeun kamungkinan bakal ngalaman masalah nalika nyarang .modaldina unsur tetep anu sanés.
  • Sakali deui, alatan position: fixed, aya sababaraha caveats kalawan ngagunakeun modals dina alat nu bagerak. Tingali dokumén pangrojong browser kami pikeun detil.
  • Kusabab kumaha HTML5 ngahartikeun semantik na, atribut autofocusHTML teu boga pangaruh dina modals Bootstrap. Pikeun ngahontal éfék anu sami, paké sababaraha JavaScript khusus:
var myModal = document.getElementById('myModal')
var myInput = document.getElementById('myInput')

myModal.addEventListener('shown.bs.modal', function () {
  myInput.focus()
})
Pangaruh animasi tina komponén ieu gumantung kana prefers-reduced-motionpamundut média. Tempo bagian gerak ngurangan tina dokuméntasi aksés kami .

Tetep maca pikeun demo sareng pedoman pamakean.

Contona

Di handap ieu conto modal statik (hartina na positiongeus displayoverridden). Kaasup header modal, awak modal (diperlukeun pikeun padding), jeung footer modal (opsional). Kami nyuhunkeun anjeun ngalebetkeun header modal sareng tindakan ngabubarkeun sabisana, atanapi nyayogikeun tindakan ngilangkeun eksplisit anu sanés.

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

Live demo

Toggle demo modal kerja ku ngaklik tombol di handap. Bakal ngageser ka handap sareng luntur ti luhur halaman.

<!-- 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">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <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>

Latar statik

Nalika backdrop disetel ka statik, modal moal nutup nalika ngaklik luar. Klik tombol di handap pikeun nyobaan eta.

<!-- 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">
        <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
        <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>

Ngagulung eusi panjang

Lamun modals jadi panjang teuing pikeun viewport pamaké atawa alat, maranéhna ngagulung bebas tina kaca sorangan. Coba demo di handap pikeun ningali naon anu kami maksud.

Anjeun oge bisa nyieun hiji modal scrollable anu ngamungkinkeun gulung awak modal ku nambahkeun .modal-dialog-scrollablekana .modal-dialog.

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

Vertikal dipuseurkeun

Tambahkeun .modal-dialog-centeredka .modal-dialogka puseur vertikal modal.

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

Tooltips na popovers

Tooltips na popovers bisa disimpen dina modals sakumaha diperlukeun. Nalika modals ditutup, sagala tooltips na popovers dina ogé otomatis mecat.

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

Ngagunakeun grid nu

Anggo sistem grid Bootstrap dina modal ku nyarang .container-fluiddina .modal-body. Teras, nganggo kelas sistem grid normal sapertos anu anjeun lakukeun di mana waé.

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

Variasi eusi modal

Boga kebat tombol anu sadayana micu modal anu sami sareng eusi anu rada béda? Anggo event.relatedTargetsareng atribut HTMLdata-bs-* pikeun ngarobih eusi modal gumantung kana tombol anu diklik.

Di handap ieu demo live dituturkeun ku conto HTML jeung JavaScript. Kanggo inpo nu leuwih lengkep, baca docs acara modal pikeun detil ngeunaan relatedTarget.

<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">
        <h5 class="modal-title" id="exampleModalLabel">New message</h5>
        <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>
var exampleModal = document.getElementById('exampleModal')
exampleModal.addEventListener('show.bs.modal', function (event) {
  // Button that triggered the modal
  var button = event.relatedTarget
  // Extract info from data-bs-* attributes
  var 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.
  var modalTitle = exampleModal.querySelector('.modal-title')
  var modalBodyInput = exampleModal.querySelector('.modal-body input')

  modalTitle.textContent = 'New message to ' + recipient
  modalBodyInput.value = recipient
})

Togél antara modal

Toggle antara sababaraha modals kalawan sababaraha panempatan pinter data-bs-targetjeung data-bs-toggleatribut. Salaku conto, anjeun tiasa ngalihkeun modal reset kecap akses ti jero modal tanda anu parantos kabuka. Punten dicatet yén sababaraha modal teu tiasa dibuka dina waktos anu sami - metode ieu ngan ukur ngagentos antara dua modal anu misah.

Buka modal munggaran
<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">
        <h5 class="modal-title" id="exampleModalToggleLabel">Modal 1</h5>
        <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">
        <h5 class="modal-title" id="exampleModalToggleLabel2">Modal 2</h5>
        <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>

Ngarobah animasi

Variabel $modal-fade-transformnangtukeun kaayaan transformasi .modal-dialogsaméméh animasi fade-in modal, $modal-show-transformvariabel nangtukeun transformasi .modal-dialogdina tungtung animasi fade-in modal.

Upami anjeun hoyong contona animasi zum-in, anjeun tiasa nyetél $modal-fade-transform: scale(.8).

Leupaskeun animasi

Pikeun modal anu ngan saukur némbongan tinimbang luntur pikeun ditingali, cabut .fadekelas tina markup modal anjeun.

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

Jangkungna dinamis

Upami jangkungna modal robih nalika dibuka, anjeun kedah nelepon myModal.handleUpdate()pikeun nyaluyukeun deui posisi modal upami aya scrollbar.

Aksesibilitas

Pastikeun pikeun nambahkeun aria-labelledby="...", ngarujuk kana judul modal, ka .modal. Salaku tambahan, anjeun tiasa masihan pedaran ngeunaan dialog modal anjeun sareng aria-describedbyon .modal. Catet yén anjeun henteu kedah nambihan role="dialog"sabab kami parantos nambihanana via JavaScript.

Embedding video YouTube

Embedding video YouTube dina modals merlukeun JavaScript tambahan teu di Bootstrap pikeun otomatis ngeureunkeun playback sareng nu sanesna. Tingali tulisan Stack Overflow ieu pikeun inpormasi anu langkung lengkep.

Ukuran pilihan

Modals gaduh tilu ukuran pilihan, sadia via kelas modifier pikeun ditempatkeun dina .modal-dialog. Ukuran ieu kick dina titik breakpoints tangtu pikeun nyingkahan scrollbars horizontal dina viewports sempit.

Ukuran Kelas Modal max-lebar
Leutik .modal-sm 300px
Default Euweuh 500px
Gede .modal-lg 800px
Ekstra badag .modal-xl 1140px

Modal standar kami tanpa kelas modifier mangrupikeun modal ukuran "sedeng".

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

Modal salayar

Override sejen nyaeta pilihan pop up a modal nu nyertakeun viewport pamaké, sadia via kelas modifier nu disimpen dina .modal-dialog.

Kelas Kasadiaan
.modal-fullscreen salawasna
.modal-fullscreen-sm-down Di handap576px
.modal-fullscreen-md-down Di handap768px
.modal-fullscreen-lg-down Di handap992px
.modal-fullscreen-xl-down Di handap1200px
.modal-fullscreen-xxl-down Di handap1400px
<!-- Full screen modal -->
<div class="modal-dialog modal-fullscreen-sm-down">
  ...
</div>

Sass

Variabel

$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:        rgba($black, .2);
$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:         $border-color;
$modal-footer-border-color:         $modal-header-border-color;
$modal-header-border-width:         $modal-content-border-width;
$modal-footer-border-width:         $modal-header-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-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);

Gelung

Modél layar pinuh responsif dihasilkeun ngaliwatan $breakpointspeta sareng loop di 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 {
        @include border-radius(0);
      }

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

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

Pamakéan

Modél plugin toggles eusi disumputkeun Anjeun on demand, via atribut data atawa JavaScript. Ogé overrides kabiasaan ngagugulung standar sarta dibangkitkeun a .modal-backdropnyadiakeun wewengkon klik pikeun dismissing modals ditémbongkeun nalika ngaklik luar modal.

Via atribut data

Togél

Aktipkeun modal tanpa nulis JavaScript. Disetél data-bs-toggle="modal"dina unsur controller, kawas tombol, babarengan jeung data-bs-target="#foo"atawa href="#foo"pikeun nargétkeun modal husus pikeun toggle.

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

Ngaleungitkeun

PHK tiasa dihontal ku dataatribut dina tombol dina modal sapertos anu dipidangkeun di handap ieu:

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

atanapi dina tombol di luar modal nganggo data-bs-targetsapertos anu dipidangkeun di handap ieu:

<button type="button" class="btn-close" data-bs-dismiss="modal" data-bs-target="#my-modal" aria-label="Close"></button>
Sanaos duanana cara pikeun ngilangkeun modal dirojong, émut yén ngabubarkeun ti luar modal teu cocog sareng pola desain dialog WAI-ARIA . Ngalakukeun ieu dina resiko sorangan.

Ngaliwatan JavaScript

Jieun modal sareng garis tunggal JavaScript:

var myModal = new bootstrap.Modal(document.getElementById('myModal'), options)

Pilihan

Pilihan bisa diliwatan via atribut data atawa JavaScript. Pikeun atribut data, tambahkeun nami pilihan ka data-bs-, sapertos dina data-bs-backdrop="".

Ngaran Tipe Default Katerangan
backdrop boolean atawa string'static' true Ngawengku unsur modal-backdrop. Alternatipna, tangtukeun staticbackdrop anu henteu nutup modal dina klik.
keyboard boolean true Nutup modal nalika konci kabur dipencet
focus boolean true Nempatkeun fokus kana modal nalika initialized.

Métode

Métode Asynchronous sareng transisi

Sadaya metode API henteu sinkron sareng ngamimitian transisi . Aranjeunna balik deui ka panelepon pas transisi dimimitian tapi saméméh éta ends . Sajaba ti éta, panggero métode dina komponén transisi bakal dipaliré .

Tempo dokuméntasi JavaScript kami pikeun inpo nu leuwih lengkep .

Pilihan ngalirkeun

Aktipkeun eusi anjeun salaku modal. Narima hiji pilihan pilihan object.

var myModal = new bootstrap.Modal(document.getElementById('myModal'), {
  keyboard: false
})

togél

Sacara manual toggles modal. Mulih ka panelepon saméméh modal sabenerna geus ditémbongkeun atawa disumputkeun (ie saméméh shown.bs.modalatawa hidden.bs.modalkajadian lumangsung).

myModal.toggle()

nempokeun

Sacara manual muka modal. Mulih ka panelepon saméméh modal sabenerna geus ditémbongkeun (ie saméméh shown.bs.modalacara lumangsung).

myModal.show()

Ogé, anjeun tiasa ngalangkungan unsur DOM salaku argumen anu tiasa ditampi dina acara modal (salaku relatedTargetharta).

var modalToggle = document.getElementById('toggleMyModal') // relatedTarget
myModal.show(modalToggle)

nyumput

Sacara manual nyumputkeun modal. Mulih ka panelepon saméméh modal geus sabenerna disumputkeun (ie saméméh hidden.bs.modalacara lumangsung).

myModal.hide()

handleUpdate

Nyaluyukeun posisi modal sacara manual upami jangkungna modalna robih nalika dibuka (upami upami aya scrollbar).

myModal.handleUpdate()

miceun

Ngancurkeun modal hiji unsur. (Ngahapus data anu disimpen dina unsur DOM)

myModal.dispose()

getInstance

Metodeu statik anu ngamungkinkeun anjeun kéngingkeun conto modal anu aya hubunganana sareng unsur DOM

var myModalEl = document.getElementById('myModal')
var modal = bootstrap.Modal.getInstance(myModalEl) // Returns a Bootstrap modal instance

getOrCreateInstance

Métode statik anu ngamungkinkeun anjeun kéngingkeun conto modal anu aya hubunganana sareng unsur DOM, atanapi ngadamel anu énggal upami henteu diinisialisasi.

var myModalEl = document.querySelector('#myModal')
var modal = bootstrap.Modal.getOrCreateInstance(myModalEl) // Returns a Bootstrap modal instance

Kajadian

Kelas modal Bootstrap ngungkabkeun sababaraha acara pikeun nyambungkeun kana fungsionalitas modal. Sadaya acara modal dipecat dina modal sorangan (ie di <div class="modal">).

Jenis acara Katerangan
show.bs.modal Kajadian ieu langsung hurung nalika showmetode conto disebut. Upami disababkeun ku klik, unsur anu diklik sayogi salaku relatedTargethak milik acara.
shown.bs.modal Kajadian ieu dipecat nalika modalna parantos katingali ku pangguna (bari ngantosan transisi CSS réngsé). Upami disababkeun ku klik, unsur anu diklik sayogi salaku relatedTargethak milik acara.
hide.bs.modal Kajadian ieu langsung dipecat nalika hidemetode conto parantos disebut.
hidden.bs.modal Acara ieu dipecat nalika modal parantos disumputkeun tina pangguna (bari ngadagoan transisi CSS réngsé).
hidePrevented.bs.modal Kajadian ieu dipecat nalika modal ditampilkeun, backdrop na nyaéta staticsareng klik di luar modal atanapi pencét konci ngewa dilakukeun nganggo pilihan keyboard atanapi data-bs-keyboarddisetel ka false.
var myModalEl = document.getElementById('myModal')
myModalEl.addEventListener('hidden.bs.modal', function (event) {
  // do something...
})