简单倒计时

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}

.box {
text-align: center;
margin: 20px auto;
width: 300px;
height: 300px;
border: 3px dashed orange;
}

p {
padding: 50px;
}
</style>
</head>
<script src="jquery.js" type="text/javascript"></script>
<body>
<div class="box">
<p class="time">倒计时</p>
<button>抢购</button>
</div>
<script type="text/javascript">
$(function () {
var now = new Date();//获取当前时间
var end = new Date(2018, 8, 12, 0, 0, 0);//结束的时间:年,月,日,分,秒(月的索引是0~11)注意月份要在当前月份-1
/*两个时间相减,得到的是毫秒ms,变成秒*/
var result = Math.floor(end - now) / 1000;

var interval = setInterval(fn, 1000); //定时器
/*封装减1秒的函数*/
function fn() {
if (result > 1) { //如果结果>1
result = result - 1;//就让结果每秒减1
var second = Math.floor(result % 60); // 计算秒 ,取余
var minite = Math.floor((result / 60) % 60); //计算分 ,换算有多少分,取余,余出多少秒
var hour = Math.floor((result / 3600) % 24); //计算小时,换算有多少小时,取余,24小时制除以24,余出多少小时
var day = Math.floor(result / (3600 * 24)); //计算天 ,换算有多少天

$(".time").html(day + "天" + hour + "小时" + minite + "分" + second + "秒");
} else {
alert("倒计时结束!");
window.clearInterval(interval);//这里可以添加倒计时结束后需要执行的事件
}
}
});
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/zyyweb/p/9629896.html