首页 > 解决方案 > Bootstrap4 初始化 Toast

问题描述

我正在使用 Bootstrap 4 中的 toasts,有一件事情困扰着我:

如果我初始化吐司

<div class="toast my-3" data-delay="2500">
    <div class="toast-header text-dark">
        //fill this later
    </div>
    <div class="toast-body text-dark">
        //fill this later
    </div>
</div>

就像在文档中一样

$(document).ready(function () {
  $(".toast").toast("show");
});

当页面加载时,toast 会按预期显示。如果我不初始化 toast,则 html 代码会占据一些位置。在我的页面底部。

如何在加载页面时不显示吐司,并且由于 html 代码而没有占据一些位置?我也尝试用 toast("hide") 或 toast("dispose") 初始化它们。

谢谢

标签: javascriptbootstrap-4

解决方案


当你写这个:

$(document).ready(function () {
  $(".toast").toast("show");
});

这意味着您希望吐司在 DOM 加载后立即显示。如果您希望 toast 有条件地出现,例如,您必须在 html 文件中创建一个按钮(单击“运行片段”并单击该按钮)。

$(document).ready(function () {
  $('#toastThis').on( "click", function() {
    $(".toast").toast("show");
  });

});
.toast {
  position: absolute;
  top: 0;
  right: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.bundle.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>


<button type="button" id="toastThis" class="btn btn-primary">Primary</button>

<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
  <div class="toast-header">
    <img src="..." class="rounded mr-2" alt="...">
    <strong class="mr-auto">Bootstrap</strong>
    <small>11 mins ago</small>
    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="toast-body">
    Hello, world! This is a toast message.
  </div>
</div>


推荐阅读