当内容滚动到视图中时,激活CSS3动画
我有一个用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>
如果在页面加载后立即快速向下滚动,则可以看到该动画。
另外,我不知道这是否重要,但是我在页面上有此条形图的多个实例。
我遇到了一个名为Waypoint的jQuery插件,但是我绝对没有运气。
如果有人可以指出正确的方向,那将非常有帮助。
谢谢!
回答:
回答:
这要求使用JavaScript或jQuery捕获滚动事件,并在每次触发滚动事件时检查该元素是否在视图中。
看到元素后,开始动画。在下面的代码中,这是通过向元素添加“开始”类来触发动画来完成的。
<div class="bar">    <div class="level eighty">80%</div>
</div>
.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;
}
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();
});
以上是 当内容滚动到视图中时,激活CSS3动画 的全部内容, 来源链接: utcz.com/qa/400087.html
