【问题标题】:How to start svg animation only when the div is in view port仅当 div 在视口中时如何启动 svg 动画
【发布时间】:2017-08-23 02:10:17
【问题描述】:

我只想在视口中可见时启动 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 容器时,此代码将使我的动画变得混乱。

【问题讨论】:

标签: jquery html css svg svg-animate


【解决方案1】:

您的问题是每次调用 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();
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2013-08-23
    • 2018-02-09
    • 2021-05-05
    • 2017-09-20
    相关资源
    最近更新 更多