1. 程式人生 > >手寫的 wow.js

手寫的 wow.js

用法:

  • 給相應的dom新增 : class與data-class
  • 設定 css
  • 應用js

class與data-class

<div class="content wow" data-class="a-fadeIn"></div>

css

.a-fadeIn{
	    	animation: fadeIn 1s both;
	    }
@keyframes fadeIn{
	0%{opacity:0};
	100%{opacity:1};
}

.wow{
	visibility: hidden;
}

js

(function(){
				let W = document.getElementsByClassName('wow');
				let L = W.length;
				//  儲存 wow的資料height與class
				let hc = [];  
				for(let i = 0;i<L;i++){
					let o = {};
					o.h = W[i].offsetTop;
					o.c = W[i].getAttribute('data-class');
					hc.push(o);
					
				}

				function wow(){
					let clientH = document.documentElement.clientHeight || document.body.clientHeight;
					let addH = clientH - 100;
					let scrollT = document.documentElement.scrollTop || document.body.scrollTop;

					for(let i = 0;i<L;i++){

						if(scrollT + addH - hc[i].h <= 0){
							if(W[i].className.indexOf(hc[i].c) > 0){
								W[i].className = W[i].className.replace('a-fadeIn',' ');
								console.log(W[i].className);
								W[i].style.visibility = 'hidden';

							}
						}else{
							if(W[i].className.indexOf(hc[i].c) < 0){
								W[i].className += " " + hc[i].c;
								W[i].style.visibility = 'visible';
							}
						}
					}
				}

				window.onscroll = wow;
				window.onload = wow;

			})();

總結:

    稍加改進wow.js,使反覆上下滑動頁面都有(fadeIn)效果.

個人能力有限,可改進的地方請指出,勿噴。