本文實例講述了原生javascript實現的全屏滾動功能。分享給大家供大家參考,具體如下:
原理:
1. 計算當前瀏覽器屏幕高度,每次翻頁顯示的內容高度即為屏幕高度
2. 對鼠標滾輪事件進行監聽,注意滾輪事件的瀏覽器兼容問題。
廢話不多說,直接上代碼
html代碼:
<div id="wrap"> <div id="main" style="top: 0;"> <div class="content num1"> <img src="https://www.bing.com/az/hprichbg/rb/SingingRingingTree_ZH-CN12497946624_1920x1080.jpg" width="100%" height="100%"> </div> <div class="content num2"> <img src="https://www.bing.com/az/hprichbg/rb/ShenandoahNP_ZH-CN9981989975_1920x1080.jpg" width="100%" height="100%"> </div> <div class="content num3"> <img src="https://www.bing.com/az/hprichbg/rb/GareSaintLazare_ZH-CN6611772290_1920x1080.jpg" width="100%" height="100%"> </div> <div class="content num4"> <img src="https://www.bing.com/az/hprichbg/rb/FriendshipSquare_ZH-CN8820626148_1920x1080.jpg" width="100%" height="100%"> </div> </div> </div>
css代碼:
#wrap{overflow: hidden;width: 100%;} #main{top: 0;position: relative;} .content{width: 100%;margin: 0;height: 100%;} .num1{background: #e8e8e8;} .num2{background: pink;} .num3{background: yellow;} .num4{background: orange;}
js代碼:
<script type="text/javascript"> var wrap = document.getElementById("wrap"); var divHeight = window.innerHeight; wrap.style.height = divHeight + "px"; var content = $(".content");//懶得寫獲取類的原生js代碼了,直接用了jquery,=。= content.height(divHeight); var startTime = 0, //開始翻屏時間 endTime = 0, now = 0; if ((navigator.userAgent.toLowerCase().indexOf("firefox")!=-1)){ //for firefox; document.addEventListener("DOMMouseScroll",scrollFun,false); } else if (document.addEventListener) { document.addEventListener("mousewheel",scrollFun,false); } else if (document.attachEvent) { document.attachEvent("onmousewheel",scrollFun); } else{ document.onmousewheel = scrollFun; } //滾動事件處理函數 function scrollFun(event){ startTime = new Date().getTime(); var delta = event.detail || (-event.wheelDelta); if ((endTime - startTime) < -1000) { //1秒內執行一次翻頁 if (delta > 0 && parseInt(main.style.top) > -divHeight * ( content.length - 1)) { //向下翻頁 now += divHeight ; turnPage(now); } if (delta < 0 && parseInt(main.style.top) < 0) { //向上翻頁 now -= divHeight ; turnPage(now); } endTime = new Date().getTime(); } else{ event.preventDefault(); } } //翻頁函數 function turnPage(now){ $("#main").animate({top:(-now+'px')},1000); //懶得寫動畫代碼了,直接用了jquery,=。= } </script>
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com