我有一个条形图,动画CSS3和动画当前激活的页面加载。
我的问题是,给定的条形图被放置在屏幕之外,由于很多内容,所以在用户滚动到它的时间,动画已经完成。
我正在寻找通过CSS3或jQuery的方式,只有当观察者看到图表时激活条形图上的CSS3动画。
<div>lots of content here,it fills the height of the screen and then some</div> <div>animating bar chat here</div>
如果您在网页加载后快速向下滚动,您可以看到它的动画。
这里是我的代码jsfiddle。此外,我不知道这是否重要,但我有几个这个条形图的页面上的实例。
我遇到了一个称为waypoint的jQuery插件,但我绝对没有运气让它工作。
如果有人能指出我的方向是正确的,这将是非常有帮助的。
谢谢!
解决方法
捕获滚动事件
这需要使用JavaScript或jQuery捕获滚动事件,检查每次滚动事件触发,以查看元素是否在视图中。
一旦元素在视图中,启动动画。在下面的代码中,这是通过向元素添加一个“start”类来触发动画。
Updated demo
HTML
<div class="bar">
<div class="level eighty">80%</div>
</div>
CSS
.eighty.start {
width: 0px;
background: #aae0aa;
-webkit-animation: eighty 2s ease-out forwards;
-moz-animation: eighty 2s ease-out forwards;
-ms-animation: eighty 2s ease-out forwards;
-o-animation: eighty 2s ease-out forwards;
animation: eighty 2s ease-out forwards;
}
jQuery
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));
}
// Check if it's time to start the animation.
function checkAnimation() {
var $elem = $('.bar .level');
// If the animation has already been started
if ($elem.hasClass('start')) return;
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('start');
}
}
// Capture scroll events
$(window).scroll(function(){
checkAnimation();
});