jQuery跳动的数字时间表动画代码

 2023-11-22    76  

     效果图:
1.gif

案例中三个方块 分别对应的是小时/分钟/秒 当任何一个方块中的数字进行改变时 对应的方块就会进行跳动 这里我们需要引入css库

image.png

html:
image.png

在js中我们先封装一个处理事件的函数 获取当前的小时 分钟 秒

image.png

然后将视图层中的demo节点获取

image.png

我们在这里进行if判断 当前demo节点中的文本 不等于现在获取的时间(字符串) 而右边获取到是数据需要通过三元运算符进行出路 

当hours小于10返回一个0 大于10返回空字符串 跟当前的hours相加 最后进行左右的赋值 并且调动shake将demo传入

image.png

shake函数也是另一个我们封装的函数 给传入的节点 进行插件中的动画类绑定 然后在后面设置一个setTimeout进行类的移除

image.png

最后在第一次载入页面的时候 通过onload调动一个clock函数

image.png

完整代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>jquery跳动的数字时间表动画代码</title>
    <link rel="stylesheet" href="./css/csshake.min.css" />
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      body {
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #d96457;
      }
      .clock {
        width: 360px;
        height: 120px;
        color: #d96457;
        font-family: "Lato", sans-serif;
        user-select: none;
      }
      .clock div {
        position: relative;
        float: left;
        background: #ffe8e8;
        border-radius: 6px;
        width: 96px;
        height: 80px;
        line-height: 80px;
        text-align: center;
        font-size: 60px;
        margin: 0px 5px;
      }
    </style>
  </head>
  <body>
    <div class="clock">
      <!-- 时 -->
      <div class="H shake shake-slow"></div>
      <!-- 分 -->
      <div class="M shake shake-slow"></div>
      <!-- 秒 -->
      <div class="S shake shake-slow"></div>
    </div>
  </body>
</html>
<script src="./js/jquery.js"></script>
<script>
  // 通过间隔定时器调用
  setInterval(function () {
    clock();
  }, 1000);
  function clock() {
    // 创建实例
    var time = new Date();
    // 获取当前的小时
    var hours = time.getHours();
    // 获取当前分钟
    var minutes = time.getMinutes();
    // 获取当前秒数
    var seconds = time.getSeconds();
    // 获取当前demo节点
    var h = $(".H"),
      m = $(".M"),
      s = $(".S");
    if (h.text() != (hours < 10 ? "0" : "") + hours) {
      h.text((hours < 10 ? "0" : "") + hours);

      shake(h);
    }
    if (m.text() != (minutes < 10 ? "0" : "") + minutes) {
      m.text((minutes < 10 ? "0" : "") + minutes);
      shake(m);
    }
    if (s.text() != (seconds < 10 ? "0" : "") + seconds) {
      s.text((seconds < 10 ? "0" : "") + seconds);
      shake(s);
    }
    console.log(seconds < 10 ? "0" : "");
  }
  //   在页面载入时调动一次加载时间
  $(document).on("load", function () {
    clock();
  });
  function shake(t) {
    t.addClass("shake-constant");
    setTimeout(function () {
      t.removeClass("shake-constant");
    }, 470);
  }
</script>


  •  标签:  

原文链接:http://1.15.94.33/?id=222

=========================================

http://1.15.94.33/ 为 “前端日记簿” 唯一官方服务平台,请勿相信其他任何渠道。