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

后端 未结 5 1602
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 17:12

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.

相关标签:
5条回答
  • 2020-12-05 17:42

    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 jsFiddle that 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. :)

    0 讨论(0)
  • 2020-12-05 17:50

    The div has a scrollTop property that you can set (and its pal, scrollLeft).

    • jsFiddle Demo

    • scrollTop on MDN

    • scrollLeft on MDN

    0 讨论(0)
  • 2020-12-05 17:51

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

    0 讨论(0)
  • 2020-12-05 18:01

    Add a div (where you want to scroll):

    <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

    0 讨论(0)
  • 2020-12-05 18:06

    As long as JavaScript is acceptable, I created a demo using jQuery that uses a known element with an ID inside the 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);
    });​
    
    0 讨论(0)
提交回复
热议问题