今日刚接触Date对象,想起了倒计时的实现,因此简单的做了一下,其效果,我做了一个小视频
欢迎留言
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#dv{font-size: 100px;text-align: center;}
</style>
</head>
<body>
<div id="dv">时间剩余0秒</div>
<p>请选择倒计时:</p>
<select name="" id="sel">
<option value="0" id="op0">0</option>
<option value="30" id="op1">30秒</option>
<option value="60" id="op2">1分钟</option>
<option value="180" id="op3">3分钟</option>
<option value="300" id="op4">5分钟</option>
</select>
<input type="button" value="开始" id="bt">
<script>
function my$(dv) {
return document.getElementById(dv);
}
var j = 0;
my$('sel').onclick = function () {
var arr=[];
var index = this.selectedIndex;
var check=this.options[index];
switch (index) {
case 0: j = 0; break;
case 1: j = 30; break;
case 2: j = 60; break;
case 3: j = 180; break;
case 4: j = 300; break;
default: break;
}
dv.innerText = `时间剩余${j}秒`;
my$('bt').onclick = function () {
clearInterval(this.interval);
this.interval = setInterval(function () {
j--;
dv.innerText = `时间剩余${j}秒`;
if (j <= 0) {
clearInterval(interval);
}
}, 1000)
if (this.value == '开始') {
this.value = '暂停';
} else if (this.value != '开始') {
this.value = '开始';
clearInterval(this.interval);
}
}
};
</script>
</body>
</html>