滚动到时启动动画

WeB*_*WeB 10 javascript css jquery animation scroll

在滚动到页面上的特定位置后,我花了一整天时间寻找一种简单的方法来启动动画.

我的css

.animation {
 width: 50%; 
 float: left; 
 position: relative; 
 -webkit-animation-name: test; 
 -webkit-animation-duration: 4s; 
 -webkit-animation-iteration-count: 3;
 -webkit-animation-fill-mode: forwards; 
 animation-name: test; 
 animation-duration: 4s; 
 animation-iteration-count: 1; 
 animation-fill-mode: forwards; }
Run Code Online (Sandbox Code Playgroud)

还有我的HTML

<div class="container">

<div class="animation">

Content goes here...

</div>

</div>
Run Code Online (Sandbox Code Playgroud)

我想知道当我滚动到类容器时如何使动画开始.

Bob*_*les 11

使用Javascript

var $window = $(window);
var $elem = $(".animation")

function isScrolledIntoView($elem, $window) {
    var docViewTop = $window.scrollTop();
    var docViewBottom = docViewTop + $window.height();

    var elemTop = $elem.offset().top;
    var elemBottom = elemTop + $elem.height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
$(document).on("scroll", function () {
    if (isScrolledIntoView($elem, $window)) {
        $elem.addClass("animate")
    }
});
Run Code Online (Sandbox Code Playgroud)

HTML

<div class="container">
    <div class="animation">Content goes here...</div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

.animation.animate {
    animation: pulse 5s infinite;//change this to whatever you want
}
Run Code Online (Sandbox Code Playgroud)

JSFiddle玩(别忘了滚动)