用原生js实现一个倒计时效果.最下面有全部源码,需要自取
js语法:
setTimeout:定时器
document.getElementById:Document的方法 getElementById()返回一个匹配特定 ID的元素。由于元素的 ID 在大部分情况下要求是独一无二的,这个方法自然而然地成为了一个高效查找特定元素的方法。
remove():可以根据Id来移除该元素.
insertAdjactHTM():js中增加HTML元素.
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title></head><body><button id="btn" onclick="startTimer()">开始计时</button><button id="closebtn" onclick="closebtn()">取消计时</button><div id="one"></div><script>let minutes = 59let seconds = 59let isShow = truefunction startTimer() {setTimeout(() => {if (isShow) {if (seconds > 0) {seconds -= 1;} else if (minutes > 0) {minutes -= 1;seconds = 59;} else {clearTimeout(timer); // 取消计时器}ShowTime();if (minutes === 0 && seconds === 0) {console.log("计时结束");} else {startTimer(); // 继续计时}}}, 1000);}function ShowTime() {const son=document.getElementById('a');const parent=document.getElementById('one')if (son) {son.remove()}if (minutes < 10 && seconds < 10) {parent.insertAdjacentHTML('afterend', "<div id='a'>0" + minutes + ":" + "0" +seconds + "</div>")} else if (minutes < 10 && seconds >= 10) {parent.insertAdjacentHTML('afterend', "<div id='a'>0" + minutes + ":" + seconds +"</div>")} else if (minutes >= 10 && seconds < 10) {parent.insertAdjacentHTML('afterend', "<div id='a'>" + minutes + ":" + "0" +seconds + "</div>")} else {parent.insertAdjacentHTML('afterend', "<div id='a'>" + minutes + ":" + seconds +"</div>")}}function closebtn() {isShow = false}ShowTime()</script></body>
</html>