窗口滚动动画

来源:互联网 发布:java代码换行 编辑:程序博客网 时间:2024/06/06 15:40

在这篇教程中,我将为你介绍如何在页面滚动时触发css动画。这种效果使用JavaScript&CSS就能做到。

Jeet Grid System website 就是使用这种小技巧的例子,当你向下滚动的时候,CSS transform animation就被触发了。

想要达到这种目的,有很多Javascript/jQuery 插件可以用,比如WOW,在这篇教程中,我将为你展示如何不适用插件做到这种效果。

The markup

那么我们开始了,首先是写好html标签,revealOnScroll类必须家在需要在滚动时触发的元素上面。

 <div data-animation="flipInX" data-timeout="400">...some content here...

data-animation这个属性声明了将会触发animation.css中animation的名字,当然添加额外的timeout参数也可以使用同样的方法,这样做当你有很多元素在同个位置被触发时很有用。

The Javascript & CSS animation

然后,我们需要定义一些变量在JavaScript文件的顶部,(不要忘记加载jQuery&Modernizr需要检查是否为触摸设备)。还有为了实现动画效果,我加载了animation.css

var $window           = $(window),win_height_padded = $window.height() * 1.1,isTouch           = Modernizr.touch;

Then we have to watch for the scroll event that will be triggered when the user is scrolling:
然后我们需要监听滚动事件,并触发我们的函数。

$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 动画。

Demo

See the Pen Trigger a CSS animation on scroll by Benoît Boucart (@benske) on CodePen.

本文根据@Benoît Boucart所译,整篇译文带有我自己的理解和意思,如果有译得不好的地方或者不对之处,还请大家指点。如需转载此译文,须注明英文出处:http://blog.webbb.be/trigger-css-animation-scroll/

译文出处:http://helkyle.com/2015/05/23/Animation-on-scroll/

1 0
原创粉丝点击