我一直在用 jQuery 创建一个图像库,一切都完成了。这些图像水平并排放置在一个 div 中,该 div 的溢出 id 被隐藏(我不想显示滚动条)。
我在链接中有两个图像向左箭头和向右箭头。现在我想做的是,当我单击向左箭头时,它应该显示上一张图像,当我单击向右箭头图像时,它应该显示下一张图像。我怀疑当使用 jQuery 单击相应的箭头图像时,我将必须向正确的方向移动滚动条。
如何做到这一点?
最佳答案
我相信你可以用scrollLeft
来做到这一点
$("#leftArrow").click(function(){
$("#divId").scrollLeft(Math.max(0, $("#divId").scrollLeft() - 100));
});
$("#rightArrow").click(function(){
$("#divId").scrollLeft(Math.min(1000, $("#divId").scrollLeft() + 100));
});
使用适当的限制而不是 0
和 1000
,并且使用图像宽度而不是 100
。
但是,查看您的示例页面,您会发现另一个问题。
您认为您的图像是这样放置的:
[Visible area] [ Overflow .... ] .=========================._ ___ ___ ___ ___ X | | | | | | X | | | | . . . | | X___|___|___|___|___|___|_X_|___|___|___| |___| "========================="
and that scrolling the visible area horizontally will make the other images become visible.
In fact, the images are being placed like this:
[Visible area] .=========================. X | | | | | | X X___|___|___|___|___|___| X "=========================" |___|___|___|___|___|___| | | | | | | | |___|___|___|___|___|___| [ Overflow ... ] ... ___ ___ ___ ___ ___ ___ | | | | | | | |___|___|___|___|___|___|
... so the horizontal scroll does no good. (The images are actually overflowing vertically! In fact, you can see this if you use the same code but with scrollTop
instead of the scrollLeft
)
The images are wrapping because they are inside a div that has an explicit width.
You can solve this by placing a second div inside your first div (the one with the overflow:none
) that is wide enough to accommodate all of your images.
As your page is, executing
javascript:
$("#images")
.css("overflow", "hidden")
.wrapInner("<div style='width:1000px'>");
就可以了。然后如果你执行
javascript:
$("#images").scrollLeft(10);
您将看到水平滚动实际上起作用了。
关于javascript - 使用 jQuery 移动滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2396525/