주요 콘텐츠로 건너뛰기 문서 탐색으로 건너뛰기
Check
in English

토스트

가볍고 쉽게 사용자 정의할 수 있는 알림 메시지인 토스트로 방문자에게 푸시 알림을 보내십시오.

토스트는 모바일 및 데스크톱 운영 체제에서 대중화된 푸시 알림을 모방하도록 설계된 가벼운 알림입니다. flexbox로 제작되어 정렬 및 위치 지정이 쉽습니다.

개요

토스트 플러그인을 사용할 때 알아야 할 사항:

  • 토스트는 성능상의 이유로 선택되어 있으므로 직접 초기화해야 합니다 .
  • 를 지정하지 않으면 토스트가 자동으로 숨겨집니다 autohide: false.
이 구성 요소의 애니메이션 효과는 prefers-reduced-motion미디어 쿼리에 따라 다릅니다. 접근성 설명서의 감소된 동작 섹션을 참조하십시오 .

기초적인

확장 가능하고 예측 가능한 토스트를 장려하려면 헤더와 본문을 권장합니다. 토스트 헤더는 display: flex를 사용하여 여백 및 플렉스박스 유틸리티 덕분에 콘텐츠를 쉽게 정렬할 수 있습니다.

토스트는 필요한 만큼 유연하고 필요한 마크업이 거의 없습니다. 최소한 "토스트된" 콘텐츠를 포함하고 닫기 버튼을 강력하게 권장하는 단일 요소가 필요합니다.

HTML
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>
.hide이전에는 스크립트 가 토스트를 완전히 숨기기 위해 클래스를 동적으로 추가했습니다 ( 가 display:none아닌 opacity:0). 이것은 이제 더 이상 필요하지 않습니다. 그러나 이전 버전과의 호환성을 위해 스크립트는 다음 주 버전까지 클래스를 계속 토글합니다(실제로 필요하지는 않지만).

라이브 예시

아래 버튼을 클릭하면 기본적으로 숨겨져 있는 알림(오른쪽 하단 모서리에 있는 유틸리티와 함께 ​​위치)을 표시합니다.

<button type="button" class="btn btn-primary" id="liveToastBtn">Show live toast</button>

<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>

다음 JavaScript를 사용하여 라이브 토스트 데모를 트리거합니다.

const toastTrigger = document.getElementById('liveToastBtn')
const toastLiveExample = document.getElementById('liveToast')
if (toastTrigger) {
  toastTrigger.addEventListener('click', () => {
    const toast = new bootstrap.Toast(toastLiveExample)

    toast.show()
  })
}

투명한

토스트는 아래에 있는 것과 섞일 수 있도록 약간 반투명합니다.

HTML
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small class="text-muted">11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

스태킹

토스트를 토스트 용기에 포장하여 쌓을 수 있습니다. 그러면 세로로 약간의 간격이 추가됩니다.

HTML
<div class="toast-container position-static">
  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small class="text-muted">just now</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      See? Just like this.
    </div>
  </div>

  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small class="text-muted">2 seconds ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Heads up, toasts will stack automatically
    </div>
  </div>
</div>

맞춤 콘텐츠

하위 구성요소를 제거 하거나 유틸리티 로 조정하거나 고유한 마크업을 추가하여 알림을 사용자 정의하십시오. 여기서는 기본값을 제거하고 Bootstrap Icons.toast-header 에서 사용자 정의 숨기기 아이콘을 추가하고 일부 flexbox 유틸리티 를 사용 하여 레이아웃을 조정하여 더 간단한 알림을 만들었습니다.

HTML
<div class="toast align-items-center" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="d-flex">
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
    <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

또는 알림에 추가 컨트롤 및 구성 요소를 추가할 수도 있습니다.

HTML
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-body">
    Hello, world! This is a toast message.
    <div class="mt-2 pt-2 border-top">
      <button type="button" class="btn btn-primary btn-sm">Take action</button>
      <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="toast">Close</button>
    </div>
  </div>
</div>

색 구성표

위의 예를 바탕으로 색상배경 유틸리티 를 사용하여 다양한 토스트 색상 구성표를 만들 수 있습니다 . 여기에 를 추가 .text-bg-primary.toast다음 .btn-close-white닫기 버튼에 추가했습니다. 선명한 가장자리를 위해 기본 테두리를 .border-0.

HTML
<div class="toast align-items-center text-bg-primary border-0" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="d-flex">
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
</div>

놓기

필요에 따라 맞춤 CSS로 토스트를 배치하세요. 상단 중앙과 마찬가지로 상단 오른쪽은 알림에 자주 사용됩니다. 한 번에 하나의 알림만 표시하려는 경우 위치 지정 스타일을 .toast.

부트스트랩 11분 전
안녕하세요, 세계입니다! 건배 메시지입니다.
HTML
<form>
  <div class="mb-3">
    <label for="selectToastPlacement">Toast placement</label>
    <select class="form-select mt-2" id="selectToastPlacement">
      <option value="" selected>Select a position...</option>
      <option value="top-0 start-0">Top left</option>
      <option value="top-0 start-50 translate-middle-x">Top center</option>
      <option value="top-0 end-0">Top right</option>
      <option value="top-50 start-0 translate-middle-y">Middle left</option>
      <option value="top-50 start-50 translate-middle">Middle center</option>
      <option value="top-50 end-0 translate-middle-y">Middle right</option>
      <option value="bottom-0 start-0">Bottom left</option>
      <option value="bottom-0 start-50 translate-middle-x">Bottom center</option>
      <option value="bottom-0 end-0">Bottom right</option>
    </select>
  </div>
</form>
<div aria-live="polite" aria-atomic="true" class="bg-dark position-relative bd-example-toasts">
  <div class="toast-container p-3" id="toastPlacement">
    <div class="toast">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small>11 mins ago</small>
      </div>
      <div class="toast-body">
        Hello, world! This is a toast message.
      </div>
    </div>
  </div>
</div>

더 많은 알림을 생성하는 시스템의 경우 쉽게 쌓일 수 있도록 래핑 요소를 사용하는 것이 좋습니다.

HTML
<div aria-live="polite" aria-atomic="true" class="position-relative">
  <!-- Position it: -->
  <!-- - `.toast-container` for spacing between toasts -->
  <!-- - `top-0` & `end-0` to position the toasts in the upper right corner -->
  <!-- - `.p-3` to prevent the toasts from sticking to the edge of the container  -->
  <div class="toast-container top-0 end-0 p-3">

    <!-- Then put toasts within -->
    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small class="text-muted">just now</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        See? Just like this.
      </div>
    </div>

    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
      <div class="toast-header">
        <img src="..." class="rounded me-2" alt="...">
        <strong class="me-auto">Bootstrap</strong>
        <small class="text-muted">2 seconds ago</small>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        Heads up, toasts will stack automatically
      </div>
    </div>
  </div>
</div>

flexbox 유틸리티를 사용하여 토스트를 수평 및/또는 수직으로 정렬할 수도 있습니다.

HTML
<!-- Flexbox container for aligning the toasts -->
<div aria-live="polite" aria-atomic="true" class="d-flex justify-content-center align-items-center w-100">

  <!-- Then put toasts within -->
  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>

접근성

토스트는 방문자 또는 사용자에게 약간의 방해를 주기 위한 것이므로 화면 판독기 및 유사한 보조 기술을 사용하는 사용자를 돕기 위해 토스트를 한 aria-live지역 에서 래핑해야 합니다 . 라이브 영역의 변경 사항(예: 알림 구성 요소 삽입/업데이트)은 사용자의 포커스를 이동하거나 사용자를 방해할 필요 없이 화면 판독기에 의해 자동으로 발표됩니다. 또한 aria-atomic="true"변경된 내용을 알리는 것보다 전체 알림이 항상 단일(원자) 단위로 발표되도록 하려면 알림 내용의 일부만 업데이트하거나 동일한 알림 내용을 표시하는 경우 문제가 발생할 수 있습니다. 나중에). 필요한 정보가 예를 들어 양식의 오류 목록과 같이 프로세스에 중요한 경우 경고 구성 요소 를 사용하십시오.토스트 대신.

알림 이 생성되거나 업데이트 되기 전에 라이브 영역이 마크업에 있어야 합니다 . 두 가지를 동시에 동적으로 생성하여 페이지에 삽입하면 일반적으로 보조 기술에 의해 발표되지 않습니다.

또한 내용에 따라 role및 레벨 을 조정해야 합니다 . aria-live오류와 같은 중요한 메시지라면 role="alert" aria-live="assertive", 그렇지 않으면 role="status" aria-live="polite"속성을 사용하세요.

표시하는 콘텐츠가 변경되면 사용자가 알림을 읽을 수 있는 충분한 시간을 갖도록 delay시간 제한 을 업데이트해야 합니다 .

<div class="toast" role="alert" aria-live="polite" aria-atomic="true" data-bs-delay="10000">
  <div role="alert" aria-live="assertive" aria-atomic="true">...</div>
</div>

를 사용할 때 autohide: false사용자가 알림을 해제할 수 있도록 닫기 버튼을 추가해야 합니다.

HTML
<div role="alert" aria-live="assertive" aria-atomic="true" class="toast" data-bs-autohide="false">
  <div class="toast-header">
    <img src="..." class="rounded me-2" alt="...">
    <strong class="me-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>

기술적으로 알림에 포커스 가능/실행 가능한 컨트롤(예: 추가 버튼 또는 링크)을 추가하는 것이 가능하지만 알림을 자동 숨기기 위해 이 작업을 수행하지 않아야 합니다. delay알림에 긴 시간 제한 을 부여하더라도 키보드 및 보조 기술 사용자는 알림에 제 시간에 도달하여 조치를 취하기 어려울 수 있습니다(토스트가 표시될 때 포커스를 받지 않기 때문). 추가 제어가 절대적으로 필요한 경우 와 함께 알림을 사용하는 것이 좋습니다 autohide: false.

CSS

변수

v5.2.0에 추가됨

Bootstrap의 진화하는 CSS 변수 접근 방식의 일부로 토스트는 이제 .toast향상된 실시간 사용자 정의를 위해 로컬 CSS 변수를 사용합니다. CSS 변수의 값은 Sass를 통해 설정되므로 Sass 사용자 정의도 계속 지원됩니다.

  --#{$prefix}toast-zindex: #{$zindex-toast};
  --#{$prefix}toast-padding-x: #{$toast-padding-x};
  --#{$prefix}toast-padding-y: #{$toast-padding-y};
  --#{$prefix}toast-spacing: #{$toast-spacing};
  --#{$prefix}toast-max-width: #{$toast-max-width};
  @include rfs($toast-font-size, --#{$prefix}toast-font-size);
  --#{$prefix}toast-color: #{$toast-color};
  --#{$prefix}toast-bg: #{$toast-background-color};
  --#{$prefix}toast-border-width: #{$toast-border-width};
  --#{$prefix}toast-border-color: #{$toast-border-color};
  --#{$prefix}toast-border-radius: #{$toast-border-radius};
  --#{$prefix}toast-box-shadow: #{$toast-box-shadow};
  --#{$prefix}toast-header-color: #{$toast-header-color};
  --#{$prefix}toast-header-bg: #{$toast-header-background-color};
  --#{$prefix}toast-header-border-color: #{$toast-header-border-color};
  

Sass 변수

$toast-max-width:                   350px;
$toast-padding-x:                   .75rem;
$toast-padding-y:                   .5rem;
$toast-font-size:                   .875rem;
$toast-color:                       null;
$toast-background-color:            rgba($white, .85);
$toast-border-width:                $border-width;
$toast-border-color:                var(--#{$prefix}border-color-translucent);
$toast-border-radius:               $border-radius;
$toast-box-shadow:                  $box-shadow;
$toast-spacing:                     $container-padding-x;

$toast-header-color:                $gray-600;
$toast-header-background-color:     rgba($white, .85);
$toast-header-border-color:         rgba($black, .05);

용법

JavaScript를 통해 알림 초기화:

const toastElList = document.querySelectorAll('.toast')
const toastList = [...toastElList].map(toastEl => new bootstrap.Toast(toastEl, option))

트리거

해고는 아래와 같이 토스트 내의data 버튼에 있는 속성 으로 달성할 수 있습니다.

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

또는 아래와 같이 사용하여 토스트 외부의 버튼에 :data-bs-target

<button type="button" class="btn-close" data-bs-dismiss="toast" data-bs-target="#my-toast" aria-label="Close"></button>

옵션

옵션은 데이터 속성이나 JavaScript를 통해 전달할 수 있으므로 에서 data-bs-와 같이 옵션 이름을 에 추가할 수 있습니다 data-bs-animation="{value}". 데이터 속성을 통해 옵션을 전달할 때 옵션 이름의 대소문자 유형을 " camelCase "에서 " kebab-case "로 변경해야 합니다. 예를 들어, data-bs-custom-class="beautifier"대신 를 사용 data-bs-customClass="beautifier"하십시오.

Bootstrap 5.2.0부터 모든 구성 요소 는 JSON 문자열로 간단한 구성 요소 구성을 수용할 수 있는 실험적 으로 예약된 데이터 속성 을 지원합니다. data-bs-config요소에 data-bs-config='{"delay":0, "title":123}'data-bs-title="456"속성이 있는 경우 최종 title값은 456이고 별도의 데이터 속성은 에 제공된 값을 재정의합니다 data-bs-config. 또한 기존 데이터 속성은 와 같은 JSON 값을 저장할 수 data-bs-delay='{"show":0,"hide":150}'있습니다.

이름 유형 기본 설명
animation 부울 true 토스트에 CSS 페이드 전환을 적용합니다.
autohide 부울 true 지연 후 토스트를 자동으로 숨깁니다.
delay 숫자 5000 알림을 숨기기 전에 지연 시간(밀리초)입니다.

행동 양식

비동기식 메서드 및 전환

모든 API 메서드는 비동기식 이며 전환 을 시작합니다 . 전환이 시작되자마자 그러나 끝나기 전에 호출자에게 돌아갑니다 . 또한 전환 구성 요소에 대한 메서드 호출은 무시 됩니다.

자세한 내용은 JavaScript 설명서를 참조하십시오 .

방법 설명
dispose 요소의 알림을 숨깁니다. 토스트는 DOM에 남아 있지만 더 이상 표시되지 않습니다.
getInstance DOM 요소와 연결된 알림 인스턴스를 가져올 수 있는 정적 메서드입니다.
예: const myToastEl = document.getElementById('myToastEl') const myToast = bootstrap.Toast.getInstance(myToastEl)부트스트랩 토스트 인스턴스를 반환합니다.
getOrCreateInstance DOM 요소와 연결된 알림 인스턴스를 가져오거나 초기화되지 않은 경우 새 인스턴스를 만들 수 있는 정적 메서드입니다.
const myToastEl = document.getElementById('myToastEl') const myToast = bootstrap.Toast.getOrCreateInstance(myToastEl)부트스트랩 토스트 인스턴스를 반환합니다.
hide 요소의 알림을 숨깁니다. 알림이 실제로 숨겨 지기 전에(즉, hidden.bs.toast이벤트가 발생하기 전에) 호출자에게 반환됩니다. 로 만든 경우 이 메서드를 수동으로 호출해야 autohide합니다 false.
isShown 토스트의 가시성 상태에 따라 부울 값을 반환합니다.
show 요소의 토스트를 표시합니다. 알림이 실제로 표시 되기 전에(즉, shown.bs.toast이벤트가 발생하기 전에) 호출자에게 반환합니다. 이 메서드를 수동으로 호출해야 합니다. 대신 알림이 표시되지 않습니다.

이벤트

이벤트 설명
hide.bs.toast hide이 이벤트는 인스턴스 메서드가 호출 되면 즉시 시작됩니다 .
hidden.bs.toast 이 이벤트는 토스트가 사용자에게 숨겨졌을 때 시작됩니다.
show.bs.toast show이 이벤트는 인스턴스 메서드가 호출 되면 즉시 발생합니다 .
shown.bs.toast 이 이벤트는 알림이 사용자에게 표시되면 시작됩니다.
const myToastEl = document.getElementById('myToast')
myToastEl.addEventListener('hidden.bs.toast', () => {
  // do something...
})