我正在尝试使用 bootstrap 5 toast 通过 javascript 创建一个新的 toast
所以基本上我到处搜索但没有任何结果,我不想切换或触发现有的 toast ,我想要的只是创建一个并显示它
没有 JavaScript 方法来创建一个实例,在 bootstrap 文档中,只有创建一个实例来初始化现有实例,有办法吗? https://getbootstrap.com/docs/5.2/components/toasts/
我感谢所有的答案
最佳答案
使用 Javascript 完全创建 toast 而不使用现有 HTML 元素的最简单方法是使用 document.createElement()
创建 HTML div,然后添加所需的类,如所述 here到它。
如果您想获得以下内容:
<div class="toast show">
<div class="toast-header">
Toast Header
</div>
<div class="toast-body">
Some text inside the toast body
</div>
</div>
你会这样做:
const toastContainer = document.createElement('div');
toastContainer.classList.add('toast', 'show');
const toastHeader = document.createElement('div');
toastHeader.classList.add('toast-header');
toastHeader.innerText = 'Toast Header';
const toastBody = document.createElement('div');
toastBody.classList.add('toast-body');
toastBody.innerText = 'Some text inside the toast body';
toastContainer.appendChild(toastHeader);
toastContainer.appendChild(toastBody);
document.body.appendChild(toastContainer);
这里我将创建的div添加到body中,当然它们也可以添加到其他div中。
关于javascript - 通过 javascript 创建新的 toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75077278/