CSS3实现整屏切换效果
页面结构
实现思路与大众方法类似,如图
每个section就是一页内容,它的大小充满了屏幕(红色区域),一个Container由多个section构成,我们通过改变container的位置,来达到页面切换的效果。container向下走,页面好像上移了,container向上走,页面就下移了。
事件监听
此时窗口里只显示一个页面,我们给其加上滚动监听,因为firefox和非firefox浏览器对滚动监听支持不同,firefox浏览器向上滚动是-120,向下滚动是120,而其他浏览器向上是5,向下是-5,所以需要作判断。
1 <!DOCTYPE html> 2 <html> 3 <head lang="ch"> 4 <meta charset="UTF-8"> 5 <meta name=”viewport” content="width=device-width, user-scalable=no, initial-scale=1.0"> 6 <title></title> 7 <style> 8 body, html{ 9 padding: 0; 10 margin: 0; 11 } 12 13 body, html { 14 height: 100%; 15 overflow: hidden; 16 } 17 18 #container, .section { 19 height: 100%; 20 } 21 22 .section { 23 background-color: #000; 24 background-size: cover; 25 background-position: 50% 50%; 26 } 27 28 #section0 { 29 background-color: #83af9b; 30 } 31 32 #section1 { 33 background-color: #764d39; 34 } 35 36 #section2 { 37 background-color: #ff9000; 38 } 39 40 #section3 { 41 background-color: #380d31; 42 } 43 44 </style> 45 </head> 46 <body> 47 <div id="container"> 48 <div class="section" id="section0"></div> 49 <div class="section" id="section1"></div> 50 <div class="section" id="section2"></div> 51 <div class="section" id="section3"></div> 52 </div> 53 54 <script src="http://code.jquery.com/jquery-latest.js"></script> 55 <script> 56 var curIndex = 0; 57 var container = $("#container"); 58 var sumCount = $(".section").length; 59 var $window = $(window); 60 var duration = 500; 61 //时间控制 62 var aniTime = 0; 63 64 var scrollFunc = function (e) { 65 //如果动画还没执行完,则return 66 if(new Date().getTime() < aniTime + duration){ 67 return; 68 } 69 e = e || window.event; 70 var t = 0; 71 if (e.wheelDelta) {//IE/Opera/Chrome 72 t = e.wheelDelta; 73 if (t > 0 && curIndex > 0) { 74 //上滚动 75 movePrev(); 76 } else if (t < 0 && curIndex < sumCount - 1) { 77 //下滚动 78 moveNext(); 79 } 80 } else if (e.detail) {//Firefox 81 t = e.detail; 82 if (t < 0 && curIndex > 0) { 83 //上滚动 84 movePrev(); 85 } else if (t > 0 && curIndex < sumCount - 1) { 86 //下滚动 87 moveNext(); 88 } 89 } 90 }; 91 92 function moveNext(){ 93 //获取动画开始时的时间 94 aniTime = new Date().getTime(); 95 container.css("transform", "translate3D(0, -" + (++curIndex) * $window.height() + "px, 0)"); 96 } 97 98 function movePrev(){ 99 //获取动画开始时的时间 100 aniTime = new Date().getTime(); 101 container.css("transform", "translate3D(0, -" + (--curIndex) * $window.height() + "px, 0)"); 102 } 103 104 function init(){ 105 /*注册事件*/ 106 if (document.addEventListener) { 107 document.addEventListener('DOMMouseScroll', scrollFunc, false); 108 }//W3C 109 window.onmousewheel = document.onmousewheel = scrollFunc;//IE/Opera/Chrome 110 111 container.css({ 112 "transition": "all 0.5s", 113 "-moz-transition": "all 0.5s", 114 "-webkit-transition": "all 0.5s" 115 }); 116 } 117 118 init(); 119 </script> 120 </body> 121 </html>