页面加载后 5 秒显示 Div

Show Div 5 Seconds after Page Load

我有一行文本包裹在 div 中,我希望最初将其隐藏,然后在页面加载 5 秒后显示。我还有一些其他功能,我不想让它在这里受到干扰。

<script type="text/javascript">
function sleep() {
    setTimeout("countdown()", 5000);
}
var ss = 6;
function countdown() {
ss = ss-1;
if (ss<0) {
window.location="http://www.mywebsite.com/";
}
else {
document.getElementById("countdown").innerHTML=ss;
window.setTimeout("countdown()", 1000);
}
}
</script>

<body onload="sleep()">Your transaction was successful.

<div id="div1"><p><em>You will be redirected to the homepage in <span id="countdown">5</span> second(s).</em></p></div>

使用setTimeout 方法在特定时间后执行任何自定义JavaScript 代码。你可以在里面展示你的div。

setTimeout(function(){ 
      $("#SomeDivId").show();
}, 5000);

回调将在 5 秒后排队到任务队列,事件循环将在执行完队列中存在的其他项目后执行它。

假设您的页面中有一个 ID 为 SomeDivId 的 div。

<div id="SomeDivId" style="display:none;">Test</div>

您可以在加载事件或 DOMContentLoaded 事件中连接执行此代码。 DOMContentLoaded 将在您的 DOM 准备好并呈现时触发,而 load 将在所有子资源(例如:images/scripts)下载后触发。

这是将其连接到 load 事件

的方法
window.onload = function ()
{
    setTimeout(function(){ 
      $("#SomeDivId").show();
    }, 5000);
};

下面是如何将它连接到 DOMContentLoaded 事件

document.addEventListener("DOMContentLoaded", function ()
    setTimeout(function(){ 
      $("#SomeDivId").show();
    }, 5000);
});

Here 是工作样本。

在页面加载时使其不可见:

<div id="div1" style="display:none"><p><em>You will be redirected to the homepage in <span id="countdown">5</span> second(s).</em></p></div>

然后在页面加载 5 秒后使其可见:

$(function(){
   setTimeout(function(){
     $('#div1').show();
   },5000);
});

以下是使用 vanilla JS 的方法。这会等待 DOM 完全加载,然后倒计时 5 秒,然后再重定向。

document.addEventListener('DOMContentLoaded', function() {
  var seconds = 5;
  var countdownEl = document.querySelector('#countdown'); 

  setInterval(function() {
    if (seconds === 0) {
      window.location = "http://www.mywebsite.com/";
      return;
    }
    countdownEl.innerHTML = --seconds;
  }, 1000);

});

http://jsbin.com/cuhepojuma/edit?html,js,output

上有一个工作示例

抱歉,如果我不清楚我需要什么。我在这里找到了解决方案。考虑到许多功能,这可能不是编码的好习惯,我对此很陌生,但它适合我的目的。我会 post 在这里为其他人提供:

<body onload="sleep()">
    <p align="center">Your transaction was successful. Thank you for your donation to...</p>
    <div align="center" id="redirect" style="visibility: hidden">
       <h4>You will be redirected to the homepage in <span id="countdown">5</span> second(s)...</h4>
    </div>

    <script type="text/javascript">
        function showRedirect() {
            document.getElementById("redirect").style.visibility = "visible";
        }
        setTimeout("showRedirect()", 2500); 
        function sleep() {
            setTimeout("countdown()", 2000);
        }
        var ss = 6;
        function countdown() {
            ss = ss-1;
            if (ss<0) {
                window.location="http://www.mywebsite.com/";
            }
            else {
                document.getElementById("countdown").innerHTML=ss;
                window.setTimeout("countdown()", 1000);
            }
        }
    </script>