JS realizes Jingdong countdown spike effect [full code]

【perfectly worked! 】In the webpage project I made, I realized the imitation Jingdong countdown effect. The method comes from the method explained in the js course by the dark horse programmer pink teacher

Explanations and caveats are all written in code comments.

js code part

 window.onload=function() {

    /* 秒杀倒计时 */
    var hour = document.querySelector(".hour");//小时的黑色盒子
    var minute = document.querySelector(".minute");//分钟的黑色盒子
    var second = document.querySelector(".second");//秒数的黑色盒子
    var inputTime = +new Date('2022-4-24 21:00:00');//倒计时的结束时间,自己设置时间,返回的是用户输入时间的总毫秒数
    //此处时间一定要比当前时间大,不然不会倒计时
    countDown();
    //2、开启定时器
    setInterval(countDown,1000);
    function countDown() {
    var nowTime = +new Date();//返回的是当前时间的总毫秒数
    //var times = (inputTime-nowTime) / 1000;//times是剩余时间的总毫秒数
    //上边写法在倒计时归零后还会继续以“0-xxx“的形式继续减少,所以改成下边写法
    var times = inputTime>nowTime?(inputTime - nowTime) / 1000:0;  //到时间就不会继续减了
    
    var h = parseInt(times / 60 / 60);//时
    h = h < 10 ? "0" + h : h;
    hour.innerHTML = h;//把剩余的小时给小时黑色盒子
    var m = parseInt(times / 60 % 60);//分
    m = m < 10 ? "0" + m : m;
    minute.innerHTML = m;
    var s = parseInt(times % 60);//秒
    s = s < 10 ? "0" + s : s;
    second.innerHTML = s;
    
} 
        }
        

html part code

 <div class="recommend_first fl">
        <a href="#">
            <div class="recom_title">臻品秒杀</div>
            <div><i class="recom_ico"></i></div> <!--此处用的是字体图标,自己去网上找然后配置即可 ,如果直接粘贴在自己的电脑上会显示不出来-->
            <h4>距离结束本场结束还有</h4>
            <div class="recom_time">
                <div class="time_num hour">01</div>
                <span class="time_point">:</span>
                <div class="time_num minute">20</div>
                <span class="time_point">:</span>
                <div class="time_num second">40</div>
            </div>
        </a>

    </div>

CSS part code

.recommend_first {
	width: 192px;
	height: 263px;
	background-color: #cc9756;
}
        .recommend_first a {
	float: left;
	width: 192px;
	height: 100%;
	background-color: #CC9756;
	color: #fff;
}

a {
	text-align: center;
    text-decoration: none;
}

.recom_ico {
	font-family: 'icomoon';
	font-size: 66px;
	color: #fff;
}

.recom_title {
	font-size: 30px;
	font-weight: 600;
	margin-top: 31px;
}

.recom_time {
	width: 180px;
	margin: 10px 0 0 4px;
}

.time_num {
	float: left;
	width: 35px;
	height: 35px;
	background-color: #000;
	margin-left: 10px;
	display: block;
	color: #fff;
	line-height: 35px;
	font-size: 24px;
}

.time_point {
	float: left;
	margin-top: -2px;
	width: 10px;
	font-size: 28px;
	color: #fff;
	padding-left: 10px;
	line-height: 35px;
}

 

Guess you like

Origin blog.csdn.net/weixin_46764819/article/details/124390470