首页 > 解决方案 > 脚本多次运行

问题描述

https://codepen.io/Yarwaa/pen/QBKqxK

我只是不明白为什么我的进度条会增加宽度,然后将其减小回 0,然后重新执行此操作。

为什么我的脚本多次运行以及如何停止此操作?

ps 如果我停止我的脚本,.off它不会一次又一次地增加宽度,但是脚本只会对第一个元素起作用,它实际上只会忽略第二个元素。

我会很高兴得到任何帮助,我实际上迷失了

来自 Codepen 的代码:

<script>
  $(document).ready(function(){
    $(window).on('scroll', function(){

      $(".progress-bar").each(function () {
        var bottom_object = $(this).position().top + $(this).outerHeight();
        var bottom_window = $(window).scrollTop() + $(window).height();
      if( bottom_window > bottom_object ){
        $(this).animate( {width: $(this).attr('aria-valuenow') + '%' }, 2000 );
    }
      });
    });
  });
</script>
<body>
  <div class="block">
    SCROLL DOWN
  </div>
  <div class="progress" id="progress">
    <div class="progress-bar progress-bar-striped bg-success" id="progress-bar" role="progressbar" style="width: 0" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
  </div>
  <div class="block">
    SCROLL DOWN
  </div>
  <div class="progress" id="progress">
    <div class="progress-bar progress-bar-striped bg-success" role="progressbar" style="width: 0" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
  </div>
</body>

标签: javascriptjquery

解决方案


基本上发生的事情是,每次滚动到元素视图时,您都在添加另一个动画事件,这似乎导致进度条卡在一个循环中,因为它们试图相互重新调整

解决此问题的一种方法是确定动画是否已经发生。

data使用方法的示例jQuery

$(".progress-bar").each(function(){
    //Setup the data for each .progress-bar
    $(this).data('scrollInitialised',false);
});
$(window).on('scroll', function(){
    $(".progress-bar").each(function () {
        var $this= $(this);

        //Check if the progress bar animation has been initialised yet
        if($this.data('scrollInitialised') === false){

            var bottom_object = $this.position().top + $this.outerHeight(),
                bottom_window = $(window).scrollTop() + $(window).height();

            //If it has not been initialised, check if it is within view
            if( bottom_window > bottom_object ){
                //Progress bar is in view, now we can animate
                $this.animate( {width: $this.attr('aria-valuenow') + '%' }, 2000 );

                //Set scrollInitialised to true so that we do not attempt to re-animate the scrollbar again
                $this.data('scrollInitialised',true);

            }

        }

    });
});

通过检查.progress-bar元素是否已scrollInitialised设置,可以防止在元素上设置多个动画


推荐阅读