页面结构
实现思路与大众方法类似,如图
每个section就是一页内容,它的大小充满了屏幕(红色区域),一个Container由多个section构成,我们通过改变container的位置,来达到页面切换的效果。container向下走,页面好像上移了,container向上走,页面就下移了。
事件监听
此时窗口里只显示一个页面,我们给其加上滚动监听,因为firefox和非firefox浏览器对滚动监听支持不同,firefox浏览器向上滚动是-120,向下滚动是120,而其他浏览器向上是5,向下是-5,所以需要作判断。
<!DOCTYPE html>
<html>
<head lang="ch">
<meta charset="UTF-8">
<meta name=”viewport” content="width=device-width, user-scalable=no, initial-scale=1.0">
<title></title>
<style>
body, html{
padding: ;
margin: ;
} body, html {
height: %;
overflow: hidden;
} #container, .section {
height: %;
} .section {
background-color: #;
background-size: cover;
background-position: % %;
} #section0 {
background-color: #83af9b;
} #section1 {
background-color: #764d39;
} #section2 {
background-color: #ff9000;
} #section3 {
background-color: #380d31;
} </style>
</head>
<body>
<div id="container">
<div class="section" id="section0"></div>
<div class="section" id="section1"></div>
<div class="section" id="section2"></div>
<div class="section" id="section3"></div>
</div> <script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var curIndex = ;
var container = $("#container");
var sumCount = $(".section").length;
var $window = $(window);
var duration = ;
//时间控制
var aniTime = ; var scrollFunc = function (e) {
//如果动画还没执行完,则return
if(new Date().getTime() < aniTime + duration){
return;
}
e = e || window.event;
var t = ;
if (e.wheelDelta) {//IE/Opera/Chrome
t = e.wheelDelta;
if (t > && curIndex > ) {
//上滚动
movePrev();
} else if (t < && curIndex < sumCount - ) {
//下滚动
moveNext();
}
} else if (e.detail) {//Firefox
t = e.detail;
if (t < && curIndex > ) {
//上滚动
movePrev();
} else if (t > && curIndex < sumCount - ) {
//下滚动
moveNext();
}
}
}; function moveNext(){
//获取动画开始时的时间
aniTime = new Date().getTime();
container.css("transform", "translate3D(0, -" + (++curIndex) * $window.height() + "px, 0)");
} function movePrev(){
//获取动画开始时的时间
aniTime = new Date().getTime();
container.css("transform", "translate3D(0, -" + (--curIndex) * $window.height() + "px, 0)");
} function init(){
/*注册事件*/
if (document.addEventListener) {
document.addEventListener('DOMMouseScroll', scrollFunc, false);
}//W3C
window.onmousewheel = document.onmousewheel = scrollFunc;//IE/Opera/Chrome container.css({
"transition": "all 0.5s",
"-moz-transition": "all 0.5s",
"-webkit-transition": "all 0.5s"
});
} init();
</script>
</body>
</html>