动画进度条

时间:2017-02-28 10:10:35

标签: javascript jquery html css

我正在处理一个进度条动画,当进度条在浏览器的视口中可见时,需要从0动画到任何百分比。当元素滚动到视图中时,动画应该始终发生,这意味着在外面滚动它必须重置动画才能开始。

这是我的非工作代码:

var $animation_elements = $('.progressAnimation');
var $window = $(window);

function check_if_in_view() {
  var window_height = $window.height();
  var window_top_position = $window.scrollTop();
  var window_bottom_position = (window_top_position + window_height);
 
  $.each($animation_elements, function() {
    var $element = $(this);
    var element_height = $element.outerHeight();
    var element_top_position = $element.offset().top;
    var element_bottom_position = (element_top_position + element_height);
 
    //check to see if this current container is within viewport
    if ((element_bottom_position >= window_top_position) &&
        (element_top_position <= window_bottom_position)) {
        $element.animate({
            "width": (600 * $($element).data("percent")) / 100
        }, 3000);
    } else {
        $element.animate({
            "width": "0"
        }, 1000)
    }
  });
}

$window.on('scroll resize', check_if_in_view);
$window.trigger('scroll');
 body{
            height:4000px;
            margin-top:800px;
        }
        .myContainer{
            width:1000px;
            margin:50px auto;
        }
        .myContainer .progressBackground{
            width:600px;
            height:40px;
            margin:0 auto 40px;
            background-color:#eaeaea;
        }
        .myContainer .progressAnimation{
            width:0;
            height:100%;
            background-color:#00f36d;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="myContainer">
        <div class="progressBackground">
            <div class="progressAnimation" data-percent="80">

            </div>
        </div>
        <div class="progressBackground">
            <div class="progressAnimation" data-percent="60">

            </div>
        </div>
    </div>

  

注意: 全屏运行代码段。

1 个答案:

答案 0 :(得分:1)

在滚动/调整大小事件中使用Javascript制作动画并不是很明智。在不限制事件的情况下,做一些非常简单的事情是明智的。

我没有深入研究你的代码以及为什么它不起作用,但我已经根据你的代码设计了一个例子,但是我使用CSS做动画(卸载动画)关闭浏览器流程),简单地改变元素&#39;当它与应有的不同时陈述。这意味着只有当元素离开屏幕时我才会将进度条缩小到0(而不是每次滚动/调整大小事件都会触发你正在做的事情)并在屏幕上显示动画进度条只有当它不在屏幕上时。

这是代码:

  var $animation_elements = $('.progressAnimation');

  $(window).on('scroll resize', function(){
    var viewportHeight = document.documentElement.clientHeight;

    $animation_elements.each(function() {
     var $el = $(this);
     var position = this.getBoundingClientRect();

     if (position.top > viewportHeight || position.bottom < 0) {
        this.inView && $el.css({ width: 0 });
      this.inView = false;
     } else {
        !this.inView && $el.css({ width: 6 * $el.data("percent") });
      this.inView = true;
     }
    });
  });

正如您所看到的,我也尽可能使用尽可能多的vanilla Javascript来尽快制作事件处理程序。

here is a working JSFiddle