我正在制作一个包含多个页面的网站。我希望它们不是不同的网页,而是同一页面上的不同 div。然后我有两个左右按钮,当用户单击特定的 div 时,它应该根据箭头向左或向右滑动。我如何使用 jQuery、HTML、CSS 来做到这一点?
我的 Div:
<div id="main-page">
</div>
<div id="about-us">
</div>
<div id="contact-us">
</div>
Divs 有一个特定的背景图像,并且它们的大小是全屏的。
我的脚本:
$("#main-page").click(function() {
$("#main-page").hide("slide", {direction: "left"}, 1000);
$("#about-us").show("slide", {direction: "right"}, 1000);
});
正如我所说,我不想那样做。我想要箭头来检查哪个 div 可以向左或向右滑动。
最佳答案
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;
});
});
关于jquery - 使用jQuery从右向左滑动div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12446281/