如何在给定的时间范围后自动打开 bootstrap 警报?

How to open bootstrap alert automatically after a given time frame?

我需要你的帮助:

我正在尝试在 加载网站 5 秒后自动页面。

我怎样才能做到这一点。我已经尽力了,但还是没能成功。

非常感谢你的帮助。

查看 Timeout

setTimeout(function() {

  //Your code here

}, 5000); //5000 miliseconds

setTimeout(function() {
  alert("Hello");
}, 5000); //In miliseconds
In 5 seconds, an alert will appear...

关键是使用以毫秒为单位的 setTimeout。

这是一个工作正常的 plunkr,警告位于右下角。

https://plnkr.co/edit/S15Fp7DcPzB5EarnWVk6

$( document ).ready(function() {
    var time = 5000 //five seconds
    $('#alert').hide();
    setTimeout(function() {
      $('#alert').show();
    }, time);
});

您可以使用setTimeout功能。这是一个例子

$('#my-alert').hide();
setTimeout(function(){ $('#my-alert').show() }, 5000);

这是fiddle:https://jsfiddle.net/pnpu2bnm/2/

我已经用 this jsFiddle

为您完成了工作

HTML:

<div class="alert alert-success" id="myAlert">
     Hello World!
</div>

CSS:

#myAlert
{
  display: none;
  position: fixed;
  bottom: 0;
  right: 0;
  width: 33%;
  margin: 20px;
}

Javascript:

setTimeout(function(){ 
    $('#myAlert').fadeIn('slow'); 
}, 5000);

确保将 javascript 放在页面底部的结束标记之前(并用标记包裹它

补充 Chris Happy 的回答:

使用一点点 jQuery 您可以将警报设置为在超时函数内可见:

$("#alertToShow").show();

setTimeout(function() {
  $("#alertToShow").show();
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
In 5 seconds, an alert will appear...

<div id = "alertToShow" class = "alert alert-danger" style = "display: none">
  This is an alert
</div>

或者,您可以研究 jQuery .append() 函数来向您的页面添加提醒。