用JavaScript實現頁面滾動效果,以及用wow.js二種方式實現網頁滾動效果
要實現效果是頁面滾動到一塊區域,該區域以動畫方式出現。
這個效果需要二點:
一:我們要先寫好一個css動畫.
二:用js的監聽頁面滑動的距離在div剛出現時給div添加動畫。
css動畫
/*設置動畫*/ @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事件,
當頁面剛好滑動到div出現時給div添加動畫,這個距離是div距離頂部的距離減去div的高度即:box.offsetTop-box.offsetHeight,或者你自己寫一個數值也行,只要保證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"//添加動畫
} }
完整代碼
<!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 就好了
