我正在制作一个网页,其中我有多个页面。我希望它们不是一个不同的网页,而是在同一页面上成为一个不同的div。然后我有两个左右按钮,当用户点击特定div时,它应该根据箭头向左或向右滑动。我怎么能用jQuery,HTML,CSS做到这一点?
My Divs:
<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。
答案 0 :(得分:2)
<强> 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;
});
});
答案 1 :(得分:0)
可能是这样的:
<div class='container'>
<div class='all-pages'>
<div class='page' id='page-1'>PAGE 1</div>
<div class='page' id='page-2'>PAGE 2</div>
<div class='page' id='page-3'>PAGE 3</div>
<div class='page' id='page-4'>PAGE 4</div>
</div>
</div>
.container {
width: 960px;
overflow: hidden;
position: relative;
}
.all-pages {
float:left;
width: 10000px;
position: relative;
left: 0;
top:0;
}
.page {
float: left;
width: 960px;
}
本质上,它与jCarousel的原理相同,不同之处在于您将元素的定位和宽度放在更大的范围内,以便每个项目填充页面:
container
- 可查看区域
all-pages
- 实际上是所有网页的“卷轴”
接下来,您需要向页面(或菜单?)添加左右按钮以滚动显示。这些必须绝对定位,以便它保持在容器视图中。
当您为左右按钮添加函数时,您只需使用jQuery动画样式函数来更改all-pages div中的left值,这将创建一个平滑的过渡。