HTML
<div id="wrapper">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<input type="button" class="next" value="Next">
<input type="button" class="prev" value="Prev">
CSS
#wrapper {
white-space: nowrap;
width: 1500px
}
.box {
width: 200px;
height: 200px;
border: thin solid red;
margin: 0 10px 0 0;
display: inline-block
}
.prev,
.next { position: fixed; top: 50% }
.prev { left: 0 }
.next { right: 0 }
JS
$(function() {
// We create an array and populate
// it with all .box left offsets
var boxLefts = [];
$('.box').each(function(i, el) {
boxLefts.push(this.offsetLeft);
});
// Now we attach an on click event handler
// to our prev/next buttons
$(".prev, .next").click(function(e) {
var dir = false,
targetLeft = -1;
// to get the current direction
// we use the className of the current clicked button
var target = e.target.className;
// we set the earlier defined direction variable
// based on the clicked button
if (target == 'next') {
dir = 1;
} else {
dir = -1;
}
// when the next-button is clicked
// we loop through the .box-offsets array
if (dir) {
// prevent the default onclick behaviour
e.preventDefault();
// get the current scroll-offset
winLeft = window.scrollX;
$.each(boxLefts, function(i, v) {
// we check that we are not at the end or beginning
// of the viewport. If we are not
// we set targetLeft to the current/matching offsets-array item.
if ((dir == 1 && winLeft < v && targetLeft < 0) || (dir == -1 && winLeft > v)) {
targetLeft = v;
}
});
// if truthy we animate the scrolling to the next/previous box-offset
if (!targetLeft) {
$('html:not(:animated), body:not(:animated)').stop().animate({
scrollLeft: targetLeft
}, 1000);
}
}
// prevent the default onclick behaviour
return false;
});
});
演示