2017-10-08 159 views
0

我有一個條形圖,動畫與CSS3和動畫當前激活當頁面加載。動畫開始時滾動

我遇到的問題是,給定的條形圖由於之前有很多內容而被放置在屏幕上,所以在用戶向下滾動到該動畫時,動畫已經完成。

我正在尋找通過CSS3或jQuery的方式,以便在查看器查看圖表時激活條形圖上的CSS3動畫。

.animation { 
 
    width: 1000px; 
 
    margin: 50px auto; 
 
} 
 

 
table { 
 
    width: 100%; 
 

 
} 
 

 
.tr-box table, 
 
.tr-box tr, 
 
.tr-box td { 
 
    border: 1px solid black; 
 
    border-collapse: collapse; 
 
} 
 

 
.tr-box tr td:first-child { 
 
    width: 20%; 
 
    text-align: center; 
 
} 
 

 
.tr-box { 
 
    margin-bottom: 20px; 
 
} 
 

 
.tr-box tr td { 
 
    padding: 10px; 
 
} 
 

 

 

 

 
.a-box-animation { 
 
    height: 40px; 
 
    width: 100%; 
 
    -webkit-animation-name: box; 
 
    animation-name: box; 
 
    -webkit-animation-duration: 6s; 
 
    animation-duration: 6s; 
 
    -webkit-animation-iteration-count: 1; 
 
    animation-iteration-count: 1; 
 
    -webkit-animation-fill-mode: forwards; 
 
    animation-fill-mode: forwards; 
 
    -webkit-animation-timing-function: ease-in-out; 
 
    animation-timing-function: ease-in-out; 
 
} 
 

 

 
@keyframes box { 
 
    0% { 
 
     width: 0%; 
 
     background-color: blue; 
 

 
    } 
 
    100% { 
 
     background-color: blue 
 
    } 
 
}
<section id="popularity"> 
 

 
     <div class="animation "> 
 

 
      <h2>Most popular books</h2> 
 
      <div class='tr-box'> 
 
       <table> 
 
        <tr> 
 
         <td>The Snowman</td> 
 
         <td> 
 
          <div class="a-box-animation"> 
 

 
          </div> 
 
         </td> 
 
        </tr> 
 
       </table> 
 
      </div> 
 
      </div> 
 

 
    </section>

=======

回答

0

你可以添加一個事件處理滾動事件,並檢查該元素是在視口中滾動時。如果是,則爲其添加一個額外的類以啓用其動畫。

function isElementInViewport (el) { 

    //special bonus for those using jQuery 
    if (typeof jQuery === "function" && el instanceof jQuery) { 
     el = el[0]; 
    } 

    var rect = el.getBoundingClientRect(); 

    return (
     rect.top >= 0 && 
     rect.left >= 0 && 
     rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */ 
     rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ 
    ); 
} 

$(window).scroll(function() { 
    if (isElementInViewport($('.box'))) { 
     $('.box').addClass('animate') 
    } 
}) 

你要一般CSS樣式提取到一類像box,並把風格有關動畫到animate類。

0

我嘗試使用滾動事件。當元素進來當前視點 - 腳本添加一個類元素

addEventListener('scroll', function(){ 
    var current_pos = window.pageYOffset ? window.pageYOffset : document.body.scrollTop; 
    if (current_pos - $('#popularity').offset().top < $(window).height() * 0.2) { 
    $('#animation-box').addClass('a-box-animation'); 
    } 
}); 

,我刪除類動畫並添加ID爲它

<div id="animation-box"></div>