京东秒杀效果
首先先利用html和css搭出架子:
* {margin: 0;padding: 0;}.box {width: 190px;height: 270px;color: #fff;text-align: center;margin: 100px auto;background-color: #d00;padding-top: 40px;box-sizing: border-box;}.box>h3 {font-size: 26px;}.box>p:nth-of-type(1) {color: rgba(255, 255, 255, .5);margin-top: 5px;}.box>i {display: inline-block;margin-top: 5px;margin-bottom: 5px;font-size: 40px;}.box>.time {display: flex;justify-content: center;margin-top: 10px;}.time>div {width: 40px;height: 40px;background: #333;line-height: 40px;text-align: center;font-weight: 700;position: relative;}.time>div::before {content: "";display: block;width: 100%;height: 2px;background: #d00;position: absolute;left: 0;top: 50%;transform: translateY(-50%);}.time>.minute {margin: 0 10px;} <div class="box"><h3>京東秒殺</h3><p>FLASH DEALS</p><i class="iconfont icon-lightningbshandian"></i><p>本場(chǎng)距離結(jié)束還剩</p><div class="time"><div class="hour">00</div><div class="minute">00</div><div class="second">00</div></div></div>再來設(shè)計(jì)其邏輯部分:
獲取相關(guān)元素
定義一個(gè)處理兩個(gè)時(shí)間差的函數(shù),需要注意的是對(duì)于小時(shí)、分鐘、秒鐘如果小于10,那么應(yīng)該在前面添加“0”來占位,最后利用對(duì)象的形式將其返回
為了實(shí)現(xiàn)其一個(gè)動(dòng)態(tài)的效果,我們可以利用setInterval(),將獲取到的時(shí)分秒全部放入進(jìn)去,使其每隔一秒就變化一次
為了用戶一打開就能看到效果,我們可以將獲取到的時(shí)分秒封裝到一個(gè)函數(shù)里,在setInterval()里和外直接調(diào)用函數(shù)即可實(shí)現(xiàn)
//1.獲取需要操作的元素const oHour = document.querySelector(".hour");const oMinute = document.querySelector(".minute");const oSecond = document.querySelector(".second");//2.處理時(shí)間差const remDate = new Date("2021-10-28 23:59:59");setTime(remDate);//開啟定時(shí)器setInterval(function() {setTime(remDate);}, 1000);//為了讓用戶一進(jìn)來就看得到效果,而不是先是三個(gè)00// 我們可以對(duì)其進(jìn)行封裝處理function setTime(remDate) {const obj = getDifferTime(remDate);// console.log(obj);//3.將差值設(shè)置給元素oHour.innerText = obj.hour;oMinute.innerText = obj.minute;oSecond.innerText = obj.second;}function getDifferTime(remDate, curDate = new Date()) {//1.得到兩個(gè)時(shí)間之間的差值(毫秒)const differTime = remDate - curDate;//2.得到兩個(gè)時(shí)間之間的差值(秒 )const differSecond = differTime / 1000;//3.利用相差的總秒數(shù) / 每一天的秒數(shù) = 相差的天數(shù)let day = Math.floor(differSecond / (60 * 60 * 24));day = day >= 10 ? day : "0" + day;//4.利用相差的總秒數(shù) / 小時(shí) % 24let hour = Math.floor(differSecond / (60 * 60) % 24);hour = hour >= 10 ? hour : "0" + hour;//5.利用相差的總秒數(shù) / 分鐘 % 60let minute = Math.floor(differSecond / 60 % 60);minute = minute >= 10 ? minute : "0" + minute;// 6.利用相差的總秒數(shù) % 秒數(shù)let second = Math.floor(differSecond % 60);second = second >= 10 ? second : "0" + second;return {day: day,hour: hour,minute: minute,second: second,}}總結(jié)
                            
                        - 上一篇: 尚硅谷git学习
 - 下一篇: 多种方式查看电脑是否支持Modern S