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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:29:00  来源:igfitidea点击:

How can I scroll programmatically a div with its own scrollbars?

csshtml

提问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 scrollTopproperty that you can set (and its pal, scrollLeft).

div 有一个scrollTop你可以设置的属性(和它的朋友,scrollLeft)。

回答by Yazz.com

Add a div (where you want to scroll):

添加一个 div(要滚动的位置):

<div id="#scroll-here">Test..</div>

and add a link like this:

并添加这样的链接:

<a href="#scroll-here">Scroll to Test</a>

if you want a smooth scroll you can check this

如果你想要一个平滑的滚动,你可以检查这个

回答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

there is this .scrollTo()method which can help you scroll through your divs. try it for more info visit here

有这种.scrollTo()方法可以帮助您滚动 div。尝试了解更多信息,请访问这里

回答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 pin the first div, and then the second pin the second div. One thing worth noting, is that to ensure the position().topis correct, you'll need to set the containing divto 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;. 希望这不是太大的问题。:)