溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JavaScript如何實(shí)現(xiàn)前端網(wǎng)頁版倒計(jì)時(shí)

發(fā)布時(shí)間:2021-03-19 14:05:06 來源:億速云 閱讀:229 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下JavaScript如何實(shí)現(xiàn)前端網(wǎng)頁版倒計(jì)時(shí),相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

效果

JavaScript如何實(shí)現(xiàn)前端網(wǎng)頁版倒計(jì)時(shí)

代碼

// An highlighted block
<!DOCTYPE html>
<html>

<head>
 <meta charset="utf-8">
 <title></title>

 <!-- css樣式 -->
 <style type="text/css">
  * {
   margin: 0;
   padding: 0;
  }

  .onsell {
   height: 400px;
   width: 200px;
   border: 1px solid #F2F2F2;
   margin: 10px;
   box-shadow: 1px 2px 4px rgba(0, 0, 0, .2);
  }

  .box {
   /* display: none; */
   float: left;
   margin: 328px 34px 0;
  }

  .box div {
   position: relative;
   display: inline-block;
   width: 40px;
   height: 40px;
   background-color: #333;
   color: #fff;
   font-size: 20px;
   text-align: center;
   line-height: 40px;
   box-shadow: 1px 2px 4px rgba(0, 0, 0, .4);
  }
 </style>

</head>

<body>
 <!-- 要求:某商品在將來某一天進(jìn)行促銷一天,利用js制作倒計(jì)時(shí)效果: 時(shí):分:秒 -->
 <div class="onsell">
  <div class="box">
   <div class="hour">00</div>
   <div class="minutes">00</div>
   <div class="seconds">00</div>
  </div>
 </div>
</body>

</html>
<script>
 window.onload = function () {
  let hour = document.querySelector('.hour')
  let minutes = document.querySelector('.minutes')
  let seconds = document.querySelector('.seconds')

  // 倒計(jì)時(shí)的時(shí)間戳 使用+將時(shí)間對(duì)象轉(zhuǎn)為時(shí)間戳 等同于Date.now()
  let wantTime = +new Date('2021-3-17 18:00:00')
  countTime()

  let timer = setInterval(() => {
   countTime()
  }, 1000)

  function countTime() {
   let currentTime = +new Date()
   if (wantTime >= currentTime) {
    let times = (wantTime - currentTime) / 1000 // 總秒數(shù) 時(shí)間戳/1000 = 秒
    let remainDay = parseInt(times / 60 / 60 / 24) // 余數(shù)取整就是剩余的天數(shù)
    console.log(remainDay);
    if (remainDay === 0) {
     if(times < 1) {
     // 倒計(jì)時(shí)完畢
     // 這里觸發(fā)操作
     }
     // 天數(shù)小于一天開始計(jì)時(shí)
     setTime(times)
    }
   } else {
    hour.innerHTML = '00'
    minutes.innerHTML = '00'
    seconds.innerHTML = '00'
   }
  }


  function setTime(time) {

   // 粗糙版
   let s = parseInt(time % 60)
   s = s < 10 ? '0' + s : s
   let m = parseInt(time / 60 % 60)
   m = m < 10 ? '0' + m : m
   let h = parseInt(time / 60 / 60 % 24)
   h = h < 10 ? '0' + h : h
   hour.innerHTML = h
   minutes.innerHTML = m
   seconds.innerHTML = s

  }

 }
</script>

以上是“JavaScript如何實(shí)現(xiàn)前端網(wǎng)頁版倒計(jì)時(shí)”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI