2017-02-28 81 views
0

我正在研究一個進度條動畫,當進度條在瀏覽器的視口內可見時,需要從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

那麼你的問題究竟是什麼? – Option

+0

動畫未在視口中執行? –

回答

1

在scroll/resize事件中使用Javascript進行動畫製作並不是很明智。在不限制事件的情況下,做一些非常簡單的事情更爲明智。

我還沒有深入研究你的代碼,爲什麼它不工作,但我已經設計了一個基於你的代碼的例子,但我正在使用CSS(卸載瀏覽器進程的動畫),以及簡單地改變元素的狀態,當它與應該是不同的時候。這意味着只有當元素熄滅屏幕(並且不是每一次都會觸發滾動/調整大小事件,這就是您正在做的事情)時,我將進度條縮小到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; 
    } 
    }); 
    }); 

正如你可以看到我也用盡可能多的香草JavaScript作爲可能使事件處理程序儘可能快。

here is a working JSFiddle