【问题标题】:Why is my javascript for a simple on-scroll number counter not working?为什么我的简单滚动数字计数器的 javascript 不起作用?
【发布时间】:2023-02-21 13:18:54
【问题描述】:

我的 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

谢谢,请在下面留下任何问题。

【问题讨论】:

    标签: javascript html css django


    【解决方案1】:

    您应该在其中包含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>
    

    【讨论】:

    • 我在头部添加了它,在body的底部也尝试过,但它似乎仍然不起作用。
    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多