原生js實作類別似fullpage的單頁/全屏滾動,jsfullpage全屏
前言
單頁/全屏滾動頁面越來越常見了,它多用於產品介紹、招聘等內容較少的簡單頁面。針對這種效果也出現了不少 jQuery 外掛程式,本文實現的效果類似於fullpage的單屏滾動,使用原生JS實現,不依賴任何js庫;
css代碼:
html,body {height:100%;}body {margin:0px;}div {height:100%;}
html代碼:
<div style="background:#FEE;"></div><div style="background:#EFE;"></div><div style="background:#EEF;"></div><div style="background:red;"></div>
js代碼:
document.addEventListener("DOMContentLoaded", function() { var body = document.body, html = document.documentElement; var itv, height = document.body.offsetHeight; var page = scrollTop() / height | 0; //視窗大小改變事件 addEventListener("resize", onresize, false); onresize(); //滾輪事件 document.body.addEventListener( "onwheel" in document ? "wheel" : "mousewheel", function(e) { clearTimeout(itv); itv = setTimeout(function() { var delta = e.wheelDelta / 120 || -e.deltaY / 3; page -= delta; var max = (document.body.scrollHeight / height | 0) - 1; if (page < 0) return page = 0; if (page > max) return page = max; move(); }, 100); e.preventDefault(); } ); //平滑滾動 function move() { var value = height * page; var diff = scrollTop() - value; (function callee() { diff = diff / 1.2 | 0; scrollTop(value + diff); if (diff) itv = setTimeout(callee, 16); })(); }; //resize事件 function onresize() { height = body.offsetHeight; move(); }; //擷取或設定scrollTop function scrollTop(v) { if (v == null) return Math.max(body.scrollTop, html.scrollTop); else body.scrollTop = html.scrollTop = v; };});
線上示範請點擊:這裡
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。