You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript创建并显示Bootstrap 5 Toast组件?

动态创建并显示Bootstrap 5 Toast的实现方法

你可以通过动态生成Toast的DOM结构,再结合Bootstrap的Toast API来实现创建并显示新Toast的需求,具体步骤如下:

核心思路

Bootstrap的Toast组件确实需要基于DOM元素初始化实例,但我们可以用JavaScript动态构建符合要求的Toast结构,再完成实例化和显示。

代码实现

1. 基础版(快速创建)

创建一个函数,动态生成Toast的HTML结构,添加到页面后初始化并显示:

function showNewToast(title, message) {
  // 构建Toast的DOM结构
  const toastHtml = `
    <div class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-bs-autohide="true" data-bs-delay="3000">
      <div class="toast-header">
        <strong class="me-auto">${title}</strong>
        <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
      <div class="toast-body">
        ${message}
      </div>
    </div>
  `;

  // 创建临时容器插入HTML,提取Toast元素
  const tempContainer = document.createElement('div');
  tempContainer.innerHTML = toastHtml;
  const toastElement = tempContainer.firstChild;

  // 将Toast添加到页面(这里选择body,也可以指定专门的容器)
  document.body.appendChild(toastElement);

  // 初始化并显示Toast
  const toast = new bootstrap.Toast(toastElement);
  toast.show();

  // 可选:Toast隐藏后自动移除DOM元素,避免冗余节点
  toastElement.addEventListener('hidden.bs.toast', () => {
    toastElement.remove();
  });
}

// 调用示例
showNewToast('提示', '这是一个动态创建的Bootstrap Toast!');

2. 进阶版(自定义配置)

如果需要更多自定义选项(比如位置、样式、不自动隐藏等),可以扩展函数参数:

function createCustomToast(options) {
  const {
    title = '通知',
    message = '',
    autohide = true,
    delay = 3000,
    positionClass = 'position-fixed bottom-0 end-0 p-3', // 右下角位置
    customClass = ''
  } = options;

  // 创建Toast容器(用于控制位置)
  const toastContainer = document.createElement('div');
  toastContainer.className = `${positionClass} ${customClass}`;

  // 构建Toast元素
  const toastElement = document.createElement('div');
  toastElement.className = 'toast';
  toastElement.setAttribute('role', 'alert');
  toastElement.setAttribute('aria-live', 'assertive');
  toastElement.setAttribute('aria-atomic', 'true');
  toastElement.setAttribute('data-bs-autohide', autohide);
  toastElement.setAttribute('data-bs-delay', delay);

  // 构建内部结构
  toastElement.innerHTML = `
    <div class="toast-header">
      <strong class="me-auto">${title}</strong>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">${message}</div>
  `;

  // 组装并添加到页面
  toastContainer.appendChild(toastElement);
  document.body.appendChild(toastContainer);

  // 初始化显示
  const toast = new bootstrap.Toast(toastElement);
  toast.show();

  // 隐藏后移除整个容器
  toastElement.addEventListener('hidden.bs.toast', () => {
    toastContainer.remove();
  });
}

// 调用示例:创建一个左上角、不自动隐藏的Toast
createCustomToast({
  title: '重要通知',
  message: '请留意这条消息,不会自动消失',
  autohide: false,
  positionClass: 'position-fixed top-0 start-0 p-3',
  customClass: 'bg-warning text-dark'
});

关键说明

  • 必须保证生成的DOM结构符合Bootstrap Toast的要求:包含.toast类,以及必要的ARIA属性。
  • 动态添加的Toast需要手动初始化new bootstrap.Toast(element),再调用show()方法。
  • 建议在Toast隐藏后移除对应的DOM元素,避免页面中积累大量无用节点。

内容的提问来源于stack exchange,提问作者rain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 13:34:39