html页面基于ajax按钮60秒倒计时
时间: 2023-06-19 21:07:35 浏览: 104
基于单片机的60秒倒计时
3星 · 编辑精心推荐
可以通过以下步骤实现:
1. 在 HTML 页面中添加一个按钮和一个显示倒计时的元素:
```
<button id="countdown-btn">开始倒计时</button>
<span id="countdown">60</span>
```
2. 在 JavaScript 中定义一个计时器,并在按钮点击时启动计时器:
```
var countdown = 60;
var countdownInterval;
document.getElementById("countdown-btn").addEventListener("click", function() {
countdownInterval = setInterval(function() {
countdown--;
document.getElementById("countdown").innerText = countdown;
if (countdown <= 0) {
clearInterval(countdownInterval);
}
}, 1000);
});
```
3. 当计时器倒计时结束时,清除计时器并重置倒计时:
```
clearInterval(countdownInterval);
countdown = 60;
document.getElementById("countdown").innerText = countdown;
```
完整的代码如下所示:
```
<button id="countdown-btn">开始倒计时</button>
<span id="countdown">60</span>
<script>
var countdown = 60;
var countdownInterval;
document.getElementById("countdown-btn").addEventListener("click", function() {
countdownInterval = setInterval(function() {
countdown--;
document.getElementById("countdown").innerText = countdown;
if (countdown <= 0) {
clearInterval(countdownInterval);
}
}, 1000);
});
</script>
```
阅读全文