好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_43122496/article/details/114941005

dy("nrwz");

查看更多关于JavaScript实现前端网页版倒计时的详细内容...

  阅读:48次