我想在视口中看到它时才启动svg动画。因为我的svg容器位于底部。我尝试使用一些方法,可以在下面看到。请告诉我如何解决它。
function isElementInViewport(elem) {
var $elem = $(elem);
// Get the scroll position of the page.
var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
var viewportTop = $(scrollElem).scrollTop();
var viewportBottom = viewportTop + $(window).height();
// Get the position of the element on the page.
var elemTop = Math.round( $elem.offset().top );
var elemBottom = elemTop + $elem.height();
return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}
function checkAnimation() {
var $elem = $('#ourprocessFlowchartContainer');
var animationTosquare =$("#contract_anim").get(0);
console.log(isElementInViewport($elem));
if (isElementInViewport($elem)==true) {
// Start the animation
animationTosquare.beginElement();
} else{
animationTosquare.endElement();
}
}
$(document).ready(function(){
$(window).scroll(function(){
checkAnimation();
});
});
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'>
<!-- SVG content omitted -->
</svg>
</div>
请帮我摆脱这个。当我访问包含svg的div容器时,此代码将使我的动画混蛋。
答案 0 :(得分: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();
});
});