2017-03-29 4 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>

나를이 없애 도와주세요. 이 코드는 svg가 포함 된 div 컨테이너를 방문 할 때 애니메이션을 얼간이로 만듭니다.

+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(); 
    }); 
});