簡體   English   中英

通過 javascript 創建新的 toast

[英]Creating new toast via javascript

我正在嘗試使用 bootstrap 5 toasts 通過 javascript 創建一個新的 toast

所以基本上我到處搜索都沒有出現,我不想切換或觸發現有的 toast,我只想創建一個並顯示它

沒有 javascript 方法來創建一個,在 bootstrap 文檔中,只有創建一個實例來初始化現有實例,有沒有辦法? https://getbootstrap.com/docs/5.2/components/toasts/

我感謝所有答案

使用 Javascript 完全創建 toast 且不使用現有 HTML 元素的最簡單方法是使用document.createElement()創建 HTML div,然后添加所需的類,如此處所述。

如果你想獲得以下內容:

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

我最終這樣做了

const toastContainer =
`<div class="position-fixed top-0 end-0 p-3 z-index-3">
<div id="toast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
        <span class="svg-icon svg-icon-2 svg-icon-primary me-3">...</span>
        <strong class="me-auto">Toast Header</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">
    Some text inside the toast body
    </div>
</div>
</div>`;
document.body.insertAdjacentHTML('afterbegin', toastContainer);
test = document.getElementById('toast');
const toast = bootstrap.Toast.getOrCreateInstance(test);
toast.show();

如果有人有更有效或更有效的方法,請隨時分享。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM