温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript如何实现前端网页版倒计时

发布时间:2021-03-19 14:05:06 来源:亿速云 阅读:206 作者:小新 栏目:开发技术

小编给大家分享一下JavaScript如何实现前端网页版倒计时,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

效果

JavaScript如何实现前端网页版倒计时

代码

// 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>
 <!-- 要求:某商品在将来某一天进行促销一天,利用js制作倒计时效果: 时:分:秒 -->
 <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')

  // 倒计时的时间戳 使用+将时间对象转为时间戳 等同于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 // 总秒数 时间戳/1000 = 秒
    let remainDay = parseInt(times / 60 / 60 / 24) // 余数取整就是剩余的天数
    console.log(remainDay);
    if (remainDay === 0) {
     if(times < 1) {
     // 倒计时完毕
     // 这里触发操作
     }
     // 天数小于一天开始计时
     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如何实现前端网页版倒计时”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI