【实例】原生 js 实现全屏滚动效果
其他,插件:http://www.dowebok.com/77.html
原理: 1. 计算当前浏览器屏幕高度,每次翻页显示的内容高度即为屏幕高度
2. 对鼠标滚轮事件进行监听,注意滚轮事件的浏览器兼容问题。
废话不多说,直接上代码
html代码:
1 <span style="font-size:18px;"><span style="font-size:14px;"><div id="wrap"> 2 <div id="main" style="top: 0;"> 3 <div class="content num1"> 4 <img src="https://www.bing.com/az/hprichbg/rb/SingingRingingTree_ZH-CN12497946624_1920x1080.jpg" width="100%" height="100%"> 5 </div> 6 <div class="content num2"> 7 <img src="https://www.bing.com/az/hprichbg/rb/ShenandoahNP_ZH-CN9981989975_1920x1080.jpg" width="100%" height="100%"> 8 </div> 9 <div class="content num3"> 10 <img src="https://www.bing.com/az/hprichbg/rb/GareSaintLazare_ZH-CN6611772290_1920x1080.jpg" width="100%" height="100%"> 11 </div> 12 <div class="content num4"> 13 <img src="https://www.bing.com/az/hprichbg/rb/FriendshipSquare_ZH-CN8820626148_1920x1080.jpg" width="100%" height="100%"> 14 </div> 15 </div> 16 </div></span></span>
css代码:
1 <span style="font-size:14px;">#wrap{overflow: hidden;width: 100%;} 2 #main{top: 0;position: relative;} 3 .content{width: 100%;margin: 0;height: 100%;} 4 .num1{background: #e8e8e8;} 5 .num2{background: pink;} 6 .num3{background: yellow;} 7 .num4{background: orange;}</span>
js代码:
1 <span style="font-size:14px;"><script type="text/javascript"> 2 var wrap = document.getElementById("wrap"); 3 4 var divHeight = window.innerHeight; 5 6 wrap.style.height = divHeight + "px"; 7 8 var content = $(".content");//懒得写获取类的原生js代码了,直接用了jquery,=。= 9 10 content.height(divHeight); 11 12 var startTime = 0, //开始翻屏时间 13 endTime = 0, 14 now = 0; 15 16 if ((navigator.userAgent.toLowerCase().indexOf("firefox")!=-1)){ 17 //for firefox; 18 document.addEventListener("DOMMouseScroll",scrollFun,false); 19 20 } 21 else if (document.addEventListener) { 22 23 document.addEventListener("mousewheel",scrollFun,false); 24 25 } 26 else if (document.attachEvent) { 27 28 document.attachEvent("onmousewheel",scrollFun); 29 30 } 31 else{ 32 33 document.onmousewheel = scrollFun; 34 35 } 36 37 //滚动事件处理函数 38 function scrollFun(event){ 39 40 startTime = new Date().getTime(); 41 42 var delta = event.detail || (-event.wheelDelta); 43 44 if ((endTime - startTime) < -1000) { 45 //1秒内执行一次翻页 46 47 if (delta > 0 && parseInt(main.style.top) > -divHeight * ( content.length - 1)) { //向下翻页 48 49 now += divHeight ; 50 51 turnPage(now); 52 53 } 54 55 if (delta < 0 && parseInt(main.style.top) < 0) { //向上翻页 56 57 now -= divHeight ; 58 59 turnPage(now); 60 61 } 62 63 endTime = new Date().getTime(); 64 65 } 66 else{ 67 68 event.preventDefault(); 69 70 } 71 72 } 73 74 //翻页函数 75 function turnPage(now){ 76 77 $("#main").animate({top:(-now+'px')},1000); 78 79 //懒得写动画代码了,直接用了jquery</span><span style="font-size:14px;">,=。= 80 } 81 </script></span>