用js 实现时间倒计时功能,倒计时10秒后,跳转到百度。页面要动态显示剩余时间
时间: 2023-06-20 11:07:08 浏览: 67
可以使用 `setInterval` 方法来实现倒计时功能,并在页面上动态显示剩余时间。下面是一个示例代码:
HTML 代码:
```html
<div>
倒计时:<span id="countdown"></span> 秒
</div>
```
JavaScript 代码:
```javascript
// 倒计时秒数
var countdownSeconds = 10;
// 获取页面上的倒计时元素
var countdownElement = document.getElementById('countdown');
// 更新倒计时元素的显示
function updateCountdown() {
countdownElement.innerText = countdownSeconds;
}
// 开始倒计时
var countdownInterval = setInterval(function() {
countdownSeconds--;
updateCountdown();
if (countdownSeconds <= 0) {
clearInterval(countdownInterval);
window.location.href = 'https://www.baidu.com';
}
}, 1000);
```
代码解释:
1. 首先定义了一个 `countdownSeconds` 变量,表示倒计时的秒数。
2. 然后获取页面上的倒计时元素,并定义了一个 `updateCountdown` 函数,用于更新倒计时元素的显示。
3. 接着使用 `setInterval` 方法来开启一个定时器,每秒钟执行一次回调函数。
4. 在回调函数里面,将 `countdownSeconds` 减去 1,然后调用 `updateCountdown` 函数来更新倒计时元素的显示。
5. 如果 `countdownSeconds` 小于等于 0,就清除定时器,并跳转到百度页面。