js倒计时5秒跳转页面
时间: 2023-09-19 14:01:01 浏览: 49
使用JavaScript编写倒计时并在5秒后跳转页面的代码如下所示:
```html
<!DOCTYPE html>
<html>
<head>
<title>倒计时页面跳转</title>
</head>
<body>
<h1>倒计时页面跳转</h1>
<p id="countdown">正在倒计时:5秒</p>
<script type="text/javascript">
var countdownElem = document.getElementById("countdown");
var countdownTime = 5;
var countdown = setInterval(function() {
countdownElem.innerText = "正在倒计时:" + countdownTime + "秒";
countdownTime--;
if (countdownTime <= 0) {
clearInterval(countdown); // 清除倒计时
window.location.href = "http://www.example.com"; // 页面跳转到指定URL
}
}, 1000);
</script>
</body>
</html>
```
以上代码中,我们首先通过`document.getElementById()`获取到倒计时元素的引用,然后设置初始倒计时时间为5秒(变量`countdownTime`)。接着使用`setInterval()`创建一个间隔为1秒的定时器,每次定时器执行时,我们更新倒计时文本,然后将倒计时时间减1。当倒计时时间小于等于0时,我们清除定时器(使用`clearInterval()`)并通过`window.location.href`将页面跳转到指定的URL(此处为"http://www.example.com")。