<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定时器实现倒计时</title>
<style>
body {
font-size: 30px;
text-align: center;
color: red;
}
</style>
<script>
window.onload = function(){
var demo = document.getElementById("demo");
var endtime = new Date("2020/02/04 12:00:00"); //最终时间
setInterval(clock, 1000); //开启定时器
function clock() {
var now = new Date(); //当前时间
var second = parseInt((endtime.getTime() - now.getTime()) / 1000); //需要倒计时的时间
var day = parseInt(second / 3600 / 24); //天数
var hour = parseInt(second / 3600 % 24); //时
var minute = parseInt(second / 60 % 60); //分
var s = parseInt(second % 60); //秒
// 三目运算添加10以下数字前面的 0
day < 10 ? day = "0"+day : day;
hour < 10 ? hour = "0"+hour : hour;
minute < 10 ? minute = "0"+minute : minute;
s < 10 ? s = "0"+s : s;
demo.innerHTML = "倒计时时间还剩:"+day+"天 "+hour+"小时 "+minute+"分钟 "+s+"秒"
}
}
</script>
</head>
<body>
<div id="demo">
</div>
</body>
</html>
进阶的民工 发布了56 篇原创文章 · 获赞 46 · 访问量 6万+ 私信 关注