用JavaScript实现页面滚动效果,以及用wow.js二种方式实现网页滚动效果css
要实现效果是页面滚动到一块区域,该区域以动画方式出现。html
这个效果须要二点:git
一:咱们要先写好一个css动画.github
二:用js的监听页面滑动的距离在div刚出现时给div添加动画。web
css动画ide
/*设置动画*/ @keyframes key { 0% { margin-left: -50px; opacity: 0; } 50% { margin-left: 50px; opacity: .5; } 100% { margin-left: 0; opacity: 1; } }
js 动画
用document.documentElement.scrollTop || document.body.scrollTop来获取页面滑动的距离,用来检测页面滑动的事件是scroll事件,spa
当页面恰好滑动到div出现时给div添加动画,这个距离是div距离顶部的距离减去div的高度即:box.offsetTop-box.offsetHeight,或者你本身写一个数值也行,只要保证Div刚出现你给它加动画便可。code
window.onscroll = function() { //检测鼠标滚轮距离顶部位置 var top = document.documentElement.scrollTop || document.body.scrollTop; console.log(top);//页面滚动时能够获得滚动的距离能够根据这个数值来决定什么时候给div绑定动画 //要设置到DIV刚显示出来时给div添加动画
if(top > (box.offsetTop-box.offsetHeight)) {
box.style.animation = "key .25s linear 2"//添加动画
} }
完整代码htm
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> img { width: 1000px; height: 800px; } .box { width: 500px; height: 500px; line-height: 500px; text-align: center; font-size: 50px; color: red; border: 1px solid; } /*设置动画*/ @keyframes key { 0% { margin-left: -50px; opacity: 0; } 50% { margin-left: 50px; opacity: .5; } 100% { margin-left: 0; opacity: 1; } } </style> </head> <body> <img src="img/7121942f07082838da2a0540b199a9014c08f11a.jpg" /> <img src="img/7121942f07082838da2a0540b199a9014c08f11a.jpg" /> <div class="box">div以动画方式出现</div> <script> var box = document.querySelector(".box"); //用js检测鼠标滚轮距离顶部位置来给div添加动画 window.onscroll = function() { //检测鼠标滚轮距离顶部位置 var top = document.documentElement.scrollTop || document.body.scrollTop; console.log(top); //要设置到DIV显示出来时给div添加动画 也能够设置一个数值只要保证div出来给它加动画便可 if(top > (box.offsetTop - box.offsetHeight)) { box.style.animation = "key .25s linear 2" //添加动画 } } </script> </body> </html>
实际工做中若是一个页面须要大量的动画上面写法就很累人了,但咱们能够用wow.js和animate.css动画库配合来实现须要的动画效果。wow.js下载地址http://www.dowebok.com/131.html,animate.css下载地址https://daneden.github.io/animate.css/
使用方法分别引入animate.css和wow.js而后在html中加上 class="wow slideInLeft" 第二个class能够自已更改.
HTML
<div class="wow slideInLeft" data-wow-duration="2s" data-wow-delay="5s"></div> <div class="wow slideInRight" data-wow-offset="10" data-wow-iteration="10"></div>
wow
是必需要添加的
slideInLeft
说明了动画的样式,是从左边滑动出来的。更多动画样式能够再这个网址https://daneden.github.io/animate.css/查看。
js
new一下调用一下方法就完成了动画效果的附加
new WOW().init();
哪里须要动画只须要在哪里的class里面写上wow slideInLeft 就行了