Html 如何使用自己的滚动条以编程方式滚动 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10634898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I scroll programmatically a div with its own scrollbars?
提问by Yazz.com
I have a HTML page with an internal DIV used for content. The internal DIV has its own scrollbars. I would like to automatically scroll to a certain position in the DIV.
我有一个带有用于内容的内部 DIV 的 HTML 页面。内部 DIV 有自己的滚动条。我想自动滚动到 DIV 中的某个位置。
How can I do this? (Note that I do NOT want to auto scroll the Window scrollbars - I already know how to do this)
我怎样才能做到这一点?(请注意,我不想自动滚动窗口滚动条 - 我已经知道如何做到这一点)
A cross platform solution is needed
需要跨平台解决方案
回答by kapa
The div has a scrollTop
property that you can set (and its pal, scrollLeft
).
div 有一个scrollTop
你可以设置的属性(和它的朋友,scrollLeft
)。
回答by Yazz.com
回答by cchana
As long as JavaScript is acceptable, I created a demo using jQuerythat uses a known element with an ID inside the div
.
只要 JavaScript 是可以接受的,我就使用 jQuery创建了一个演示,它使用了一个在div
.
$(function() {
var testOffset = $('#test').offset(),
scrollOffset = $('#scroll').offset();
$('#scroll').scrollTop(testOffset.top - scrollOffset.top);
});?
If you only know how far, in terms of pixels, rather than to a specific element, it could be adapted to:
如果你只知道多远,就像素而言,而不是特定元素,它可以适用于:
$(function() {
$('#scroll').scrollTop(100);
});?
回答by Neji
回答by Richard
I would recommend having a look at the scrollTo jQuery plugin. It's a really handy plugin that allows you to animate a scroll within any element. I've setup a small example in jsFiddlethat demonstrates how it works. The example shows how you "scroll to" the third p
in the first div
, and then the second p
in the second div
. One thing worth noting, is that to ensure the position().top
is correct, you'll need to set the containing div
to have a position: relative;
. Hopefully this isn't too much of a problem though. :)
我建议看看scrollTo jQuery plugin。这是一个非常方便的插件,允许您在任何元素内为滚动设置动画。我在jsFiddle中设置了一个小例子来演示它是如何工作的。这个例子说明了如何“滚动到”第三个p
第一div
,然后第二个p
在第二div
。值得注意的一件事是,为了确保position().top
正确,您需要将包含设置div
为具有position: relative;
. 希望这不是太大的问题。:)