需要引入jQuery以及iscroll.js
外层容器.ctn的height取决于有多少个滚动元素.box 高度为.box的个数*100% 例如有4个.box 则高度为 4*100%
滚动元素因为是满屏切换,所以高度为总容器的 n分之一 。如有四个.box元素。则每个的高度为 四分之一 即25%
JS部分:
if (window.addEventListener) {
var newScroll = new IScroll("#container", {
mouseWheel: true,
momentum: false,
snap: true
})
} else {
// IE7-IE8
var newScroll = {
content: $("#container > div"),
currentPage: {
pageY: 0
},
next: function() {
this.currentPage.pageY++;
var index = this.currentPage.pageY;
if (index > 9) {
index = 9;
return this;
}
this.content.animate({
top: -100 * index + "%"
}, this.scrollEnd);
},
prev: function() {
this.currentPage.pageY--;
var index = this.currentPage.pageY;
if (index < 0) {
index = 0;
return this;
}
this.content.animate({
top: -100 * index + "%"
}, this.scrollEnd)
},
goToPage: function(x, y) {
this.currentPage.pageY = y;
this.content.animate({
top: -100 * y + "%"
}, this.scrollEnd);
},
on: function(name, fn) {
this[name] = fn;
}
}
}
$(".downbtn").on("click", function() {
newScroll.next()
});
$("#nav li").on("click", function() {
newScroll.goToPage(0, $(this).attr("data-index") * 1)
});
newScroll.on("scrollEnd", function() {
var pageY = newScroll.currentPage.pageY;
$("#nav li").removeClass("navon");
$("#nav li[data-index=" + pageY + "]").addClass("navon");
$(".box").eq(pageY).addClass("active");
});
$(document).bind("keyup", function(event) {
var code = event.keyCode;
if (code == 38) {
newScroll.prev()
} else if (code == 40) {
newScroll.next()
}
});
newScroll.goToPage(0, 0);
CSS部分:
.container {
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
}
.ctn {
height:400%;
position:absolute;
left:0;
right:0;
}
.box {
height:25%;
position:relative;
overflow:hidden;
display:block;
}
.box1 {
background-color:#ccc;
}
.box2 {
background-color:red;
}
.box3 {
background-color:blue;
}
.box4 {
background-color:green;
}
#nav {
position:fixed;
top:100px;
left:40px;
list-style:none;
}
#nav li {
width:20px;
height:20px;
border:1px solid #000;
background-color:#fff;
text-align:center;
cursor:pointer;
margin-bottom:10px;
}
#nav li.navon {
background-color:#000;
border:1px solid #fff;
color:#fff;
}
.downbtn {
display:block;
cursor:pointer;
width:53px;
height:32px;
background:url(icon-down.png) left top no-repeat;
text-indent:-9999px;
overflow:hidden;
position:absolute;
left:50%;
bottom:5%;
margin-left:-26px;
}
HTML部分: