网络编程
位置:首页>> 网络编程>> JavaScript>> JavaScript实现一个多少秒后自动跳转的页面(案例代码)

JavaScript实现一个多少秒后自动跳转的页面(案例代码)

作者:小杨不香菜  发布时间:2024-07-13 12:03:13 

标签:js,自动跳转

JavaScript实现一个多少秒后自动跳转的页面

要求用js简单实现一个多少秒后自动跳转的页面

效果是这样的

JavaScript实现一个多少秒后自动跳转的页面(案例代码)

不多说,上代码。

这是HTML代码部分。

<div class="box">
       <h3>支付成功</h3>
       <a href="https://blog.csdn.net/Quentin0823/article/details/123184824?spm=1001.2014.3001.5502" rel="external nofollow" >
           <span id="num">3</span>
           <span>秒后自动跳转</span>
       </a>
   </div>

这是JS代码部分。

<script>
       function jump() {
           var time = document.getElementById('num');
           var _num = time.innerHTML;
           if (_num > 0) {
               _num--;
               time.innerHTML = _num;
           } else {
               location.assign("https://blog.csdn.net/Quentin0823/article/details/123184824?spm=1001.2014.3001.5502")
           }
       }
       setInterval(jump, 1000)
   </script>

要实现定时跳转,就能知道需要用到setTimeout()来实现计时,还需要能够跳转,要用到location.assign()。首先想到的大概就是一下几步

  • 编写定时跳转的HTML页面

  • 获取指定的秒数,并减1写入页面

  • 当秒数大于0时,利用 setTimeout() 循环倒计时。

  • 当秒数小于等于0时,利用 location.assign() 跳转到指定的URL地址中。

最主要的还是方法和思路吧!可能代码优化的不太够,希望能有所帮助,大家有更好的写法也可以分享出来,共同学习,共同进步吖~

PS:js实现几秒倒计时之后自动跳转页面

点击按钮之后 自动跳转到百度

<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>

<body>
   <button>跳转百度</button>
   <div></div>

<script>
       var btn = document.querySelector('button');
       var div = document.querySelector('div')
           btn.addEventListener('click', function() {
               var times = 5;
               setInterval(function() {
                   if (times == 0) {
                       location.href = 'http://www.baidu.com';
                       times = 5;
                   } else {
                       div.innerHTML = '还剩' + times + '秒自动跳转'
                       times--;
                   }

}, 1000)
       })
       // 五秒后直接跳转
       var times = 5
       setInterval(function() {
           if (times == 0) {
               location.href = 'http://www.baidu.com';
               times = 5;
           } else {
               div.innerHTML = '还剩' + times + '秒自动跳转'
               times--;
           }

}, 1000)
   </script>
</body>

</html>

来源:https://blog.csdn.net/Quentin0823/article/details/123185847

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com