欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

JS实现倒计时三秒钟跳转到新的页面

发布时间:2024/9/19 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 JS实现倒计时三秒钟跳转到新的页面 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

代码如下:

<div id="box"><p>页面在<span id="Os">5</span>s后跳转</p> </div> <script>var Os=document.getElementById("Os");var num=5;var timer=setInterval(function () {num--;Os.innerText=num;if(num==0){window.location.href="https://www.baidu.com/";}},1000) </script>

在js代码里,我用了setInterval() 方法,此方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

setInterval(code, milliseconds); (code是一个代码串,milliseconds(时间),多少时间调用一次) setInterval(function, milliseconds, param1, param2, ...) (param是传给执行函数的其他参数,根据情况写)

这个方法对函数或代码串会一直调用,直到 clearInterval() 被调用或窗口被关闭。

clearInterval() 方法

可取消由 setInterval() 函数设定的定时执行操作

<div id="box"><p>页面在<span id="Os">5</span>s后跳转</p><button id="btn" onclick="stop()">停止</button> </div> <script>var Os=document.getElementById("Os");var num=5;var timer=setInterval(function () {num--;Os.innerText=num;if(num==0){window.location.href="https://www.baidu.com/";}},1000)function stop() {clearInterval(timer);} </script>

上个代码,加了个停止。

若你只想执行一次那就用,setTimeout() 方法,和setInterval() 方法使用方法一样,这个只执行一次

页面跳转的方法:

window.location.href="/url" 当前页面打开URL页面    

还有好多种跳转的方法:self.location.href="/url" 当前页面打开URL页面
                                        location.href="/url" 当前页面打开URL页面

                                        this.location.href="/url" 当前页面打开URL页面
                                        parent.location.href="/url" 在父页面打开新页面
                                        top.location.href="/url" 在顶层页面打开新页面

原文链接:https://blog.csdn.net/weixin_43937528/article/details/89336188

总结

以上是生活随笔为你收集整理的JS实现倒计时三秒钟跳转到新的页面的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。