微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在几秒钟后使用 Bootstrap 自动关闭警报?

如何解决如何在几秒钟后使用 Bootstrap 自动关闭警报?

我开发了一个 Python/Flask 应用程序,但在实现 Bootstrap 警报时遇到了问题:

  • 可通过关闭按钮关闭
  • 如果不采取任何行动,则在 2 秒后淡出并关闭

代码

<div class="container">
        {% for message in get_flashed_messages() %}   
        <script>       
          function close_alert()
          {
            document.getElementById("my_alert").close()
          }
          setTimeout("close_alert()",2000)
        </script>
        <div id="my_alert" class="alert alert-primary alert-dismissible fade show" role="alert">
          <strong>{{message}}</strong>
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
        {% endfor %}
</div>

我是 Bootstrap 的新手,希望得到任何支持

谢谢!

解决方法

使用 Bootstrap 方法来实现您的目标,看看here

$('#show').click(function(){
  $('#alert').removeClass('d-none')
  setTimeout(function(){
    $('.alert').alert('close')
  },2000)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
 
<div class="container">
  <div id="alert" class="alert alert-primary mt-2 d-none" role="alert">
    This is a primary alert—check it out!
  </div>
</div>
   
<center><https://stackoverflow.com/posts/68165975/edit#button class="btn btn-primary mt-2" id="show">
  show alert and close it in 2s
 </button></center>

,

我建议使用“toast”——这是一个适用于您的用例的 UI 组件:https://getbootstrap.com/docs/4.2/components/toasts/

enter image description here 来自 Bootstrap 文档:

<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 class="text-muted">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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。