jquery 为什么我的javascript的一个简单的滚动数字计数器不工作?

egdjgwm8  于 2023-02-21  发布在  jQuery
关注(0)|答案(1)|浏览(98)

我的javascript应该会在数字向下滚动时产生反效果,然而,它似乎不起作用,我也不知道为什么。下面是我的简短html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
    <style>
        .fake-div {
          width:100%;
          height: 1280px;
          position:relative;
        }
    </style>
    
</head>
<body>

  <div class="fake-div">
  </div>
  <div id="counter">
      <div class="counter-value" data-count="300">0</div>
      <div class="counter-value" data-count="400">100</div>
      <div class="counter-value" data-count="1500">200</div>
  </div>
  <div class="fake-div">
  </div>

  
  <script> 
        var a = 0;
        $(window).scroll(function() {

          var oTop = $('#counter').offset().top - window.innerHeight;
          if (a == 0 && $(window).scrollTop() > oTop) {
            $('.counter-value').each(function() {
              var $this = $(this),
                countTo = $this.attr('data-count');
              $({
                countNum: $this.text()
              }).animate({
                  countNum: countTo
                },

                {

                  duration: 2000,
                  easing: 'swing',
                  step: function() {
                    $this.text(Math.floor(this.countNum));
                  },
                  complete: function() {
                    $this.text(this.countNum);
                    //alert('finished');
                  }

                });
            });
            a = 1;
          }

        });
      </script>
</body>
</html>

代码取自下面的网站。虽然它是完全相同的代码,但它似乎无法在我的桌面上工作。
https://codepen.io/dmcreis/pen/VLLYPo
谢谢,如有任何问题,请在下方留言。

arknldoa

arknldoa1#

您应该将jquery包含在其中。

//Note: This is for version 3.5.0. You can change it here \/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>

相关问题