京东官网效果
jd有个小bug,倒计时刷新时间会重新回到05:10:59������
H5+CSS部分
<style>
* {
margin: 0;
padding: 0;
}
.countdown {
width: 190px;
height: 260px;
margin: 0 auto;
background: #E83632;
background: url(http://misc.360buyimg.com/mtd/pc/index_2019/1.0.0/assets/img/4a15d8883775742e3efbb850ae14def7.png);
}
.countdown .title {
color: #fff;
font-size: 30px;
text-align: center;
font-weight: bold;
padding-top: 30px;
}
.countdown .desc {
color: #fff;
font-size: 14px;
text-align: center;
margin-top: 100px;
vertical-align: middle;
}
.countdown .desc>strong {
font-size: 18px;
vertical-align: middle;
margin-right: 8px;
}
.countdown .time {
width: 80%;
height: 30px;
margin: 0 auto;
margin-top: 10px;
color: #fff;
font-size: 20px;
margin-left: 25px;
}
.countdown .time>span {
width: 30px;
height: 30px;
display: inline-block;
background: #2f3430;
margin-left: 5px;
text-align: center;
font-weight: bold;
padding-top: 4px;
}
</style>
<div class="countdown">
<div class="title">京东秒杀</div>
<div class="desc">
<strong id="start"></strong>点倒计时
</div>
<div class="time">
<span class="h">1</span>
:
<span class="m">1</span>
:
<span class="s">1</span>
</div>
</div>
需求: 京东倒计时,两个小时一场.
分析:
获取当前时间,并提取小时数。
秒杀开始时间为整点数,而且为偶数,如果当前小时数为奇数,退一位即可。
秒杀结束时间:获取的小时数+2即为结束时间
倒计时:秒杀结束时间-当前时间,在算出时间差即可。
实现
<script>
/*
需求: 京东倒计时,两个小时一场.
12-13-14-15-16--17-18-20-22
*/
/******计算出当前是x点场*****/
function fn() {
// 1 获取当前时间
var date = new Date();
// date.setHours(19)
// 2 取出小时
var hours = date.getHours();
// console.log(hours);
// 3 因为是2h一场,都是偶数场,出现奇数场,则减1
hours = hours % 2 != 0 ? hours - 1 : hours;
// console.log(hours);
// 4 小于10 则补0操作
hours < 10 && (hours = '0' + hours);
// 5 放置到场数中
var h = document.querySelector('#h');
h.innerHTML = hours;
// 6 设置结束时间
var endDate = new Date();
endDate.setHours(hours - 0 + 2);
endDate.setMinutes(0);
endDate.setSeconds(0)
// 7 结束时间减去当前时间,得到差值
var diffMs = endDate - date;
// console.log(diffMs);
// 8 计算输出小时分钟和秒数
var h = parseInt(diffMs / 1000 / 60 / 60);
var m = parseInt(diffMs / 1000 / 60 % 60) // 150 两小时 120 余 30
var s = parseInt(diffMs / 1000 % 60);
// 9 获取节点放到页面中
document.querySelector('.h').innerHTML = h;
document.querySelector('.m').innerHTML = m;
document.querySelector('.s').innerHTML = s;
}
fn();
setInterval(fn, 1000)
</script>