脚本多次运行

时间:2018-07-19 01:30:48

标签: javascript jquery

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

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

为什么我的脚本可以多次工作,以及如何停止此操作?

p.s如果我用.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>

1 个答案:

答案 0 :(得分:4)

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

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

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,可以防止在该元素上设置多个动画