经常在产品官网可以体验到随着鼠标滚动页面的内容会加上各种动画效果。
当你向下滚动的时候,CSS的transform、animation就被触发了.
首先是写好HTML标签,revealOnScroll 类必须家在需要在滚动时触发的元素上面。
<div data-animation="flipInX" data-timeout="400">...some content here...
data-animation这个属性声明了将会触发animation.css中animation的名字,当然添加额外的timeout参数也可以使用同样的方法,这样做当你有很多元素在同个位置被触发时很有用。
然后需要定义一些变量在JavaScript文件的顶部,(不要忘记加载jQuery和Modernizr需要检查是否为触摸设备)。还有为了实现动画效果,我加载了animation.css
var $window = $(window),
win_height_padded = $window.height() * 1.1,
isTouch = Modernizr.touch;
然后我们需要监听滚动事件,并触发我们的函数。
$window.on('scroll', revealOnScroll);
在revealOnScroll函数里面我们检查元素是否需要执行动画,如果是,animation类就会添加,并触发了CSS animation。
function revealOnScroll() {
var scrolled = $window.scrollTop();
$(".revealOnScroll:not(.animated)").each(function () {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded > offsetTop) {
if ($this.data('timeout')) {
window.setTimeout(function(){
$this.addClass('animated ' + $this.data('animation'));
}, parseInt($this.data('timeout'),10));
} else {
$this.addClass('animated ' + $this.data('animation'));
}
}
});
}
还有另一个小技巧,当元素不可见的时候,animation类被移掉,这样在一次请求里面多次animate动画。