js实现倒计时效果
程序员文章站
2022-03-22 10:23:15
距离双十一,还有
00天 00时
<h4 class="title">距离双十一,还有</h4>
<div class="time-item">
<span><span id="day">00</span>天</span>
<strong><span id="hour">00</span>时</strong>
<strong><span id="minute">00</span>分</strong>
<strong><span id="second">00</span>秒</strong>
</div>
//
<script>
//目标时间的时间戳
var endDate = new Date('2020-11-11 0:0:0');
var end = endDate.getTime();
//获取需要的元素
var spanday = document.getElementById('day');
var spanhour = document.getElementById('hour');
var spanminute = document.getElementById('minute');
var spansecond = document.getElementById('second');
//开启定时器
setInterval(countdown, 1000);
countdown();
//倒计时
function countdown() {
//当前时间戳
var nowDate = new Date();
var now = nowDate.getTime();
//计算时间差(毫秒)
var leftTime = end - now;
//相差秒数
leftTime /= 1000;
// 求 相差的天数/小时数/分钟数/秒数
var day, hour, minute, second;
//计算时间
day = Math.floor(leftTime / 60 / 60 / 24);
hour = Math.floor(leftTime / 60 / 60 % 24);
minute = Math.floor(leftTime / 60 % 60);
second = Math.floor(leftTime % 60);
//设置盒子里面的内容
spanday.innerText = day;
spanhour.innerText = hour;
spanminute.innerText = minute;
spansecond.innerText = second;
}
</script>
注意:里面我没有写css样式,如果你想效果好看一点,你可以自己加上一些样式上去。
本文地址:https://blog.csdn.net/no_one_but_you/article/details/109558238