2017-03-29 2 views
0

ビューポートに表示されているときだけ、svgアニメーションを開始します。私のSVGコンテナは底にあるので。私は以下に示すいくつかの方法を試してみました。親切に私にそれを修正する方法をお願いします。divがビューポートにあるときだけsvgアニメーションを開始する方法

function isElementInViewport(elem) { 
 
\t var $elem = $(elem); 
 
\t // Get the scroll position of the page. 
 
\t var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html'); 
 
\t var viewportTop = $(scrollElem).scrollTop(); 
 
\t var viewportBottom = viewportTop + $(window).height(); 
 

 
\t // Get the position of the element on the page. 
 
\t var elemTop = Math.round($elem.offset().top); 
 
\t var elemBottom = elemTop + $elem.height(); 
 

 
\t return ((elemTop < viewportBottom) && (elemBottom > viewportTop)); 
 
} 
 
function checkAnimation() { 
 
\t var $elem = $('#ourprocessFlowchartContainer'); 
 
\t var animationTosquare =$("#contract_anim").get(0); 
 
\t console.log(isElementInViewport($elem)); 
 
\t if (isElementInViewport($elem)==true) { 
 
\t \t // Start the animation 
 
\t \t animationTosquare.beginElement(); 
 
\t } else{ 
 
\t \t animationTosquare.endElement(); 
 
\t } 
 
} 
 

 
$(document).ready(function(){ 
 

 
$(window).scroll(function(){ 
 
\t \t checkAnimation(); 
 
\t }); 
 
});
body { 
 
    background-color: #555; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id='ourprocessFlowchartContainer' class="ourprocessFlowchartContainer"> 
 
    <svg id="processFlowchart" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" viewBox = '0 0 740 300'> 
 
\t <!-- SVG content omitted --> 
 
    </svg> 
 
</div>

この取り除くために私を助けてください。このコードは、私のdivコンテナにsvgが入っているのを見て、私のアニメーションを変えてしまいます。

+0

あなたのコードはどこにありますか? – hungerstar

+0

https://jsfiddle.net/RandyRam/kpfgp8k7/ – Ram

答えて

0

問題は、checkAnimation()が呼び出されるたびにアニメーションを再トリガーしていることです。私はこれが起こらないことを確認するフラグを追加しました。ここでの作品:

https://jsfiddle.net/FrancisMacDougall/bfngjsg0/

var waiting = true; 
function checkAnimation() { 
    var $elem = $('#ourprocessFlowchartContainer'); 
    var animationTosquare =$("#contract_anim").get(0); 
    console.log(isElementInViewport($elem)); 
    if (isElementInViewport($elem)==true) { 
    // Start the animation 
    if(waiting) { 
     animationTosquare.beginElement(); 
     waiting = false; 
    } 
    } else { 
    if(!waiting) { 
     animationTosquare.endElement(); 
     waiting = true; 
    } 
    } 
} 

$(document).ready(function(){ 
checkAnimation(); 
$(window).scroll(function(){ 
    checkAnimation(); 
    }); 
}); 
関連する問題