How to scroll an item inside a scrollable div to the top

前端 未结 5 877
旧巷少年郎
旧巷少年郎 2020-12-09 10:03

I have a #contact-list-scroller div that scrolls in the page. Based on a contact_XXXX ID I\'d like the #contact-list-scroller scroll position to bet set to make sure the con

相关标签:
5条回答
  • 2020-12-09 10:18

    After trying all of the above with no success I found this at W3schools:

    var elmnt = document.getElementById("Top");
    elmnt.scrollIntoView();

    0 讨论(0)
  • 2020-12-09 10:28

    Take a look at the jquery scrollTo plugin - you can use it to scroll to a specific DOM element http://flesler.blogspot.com/2007/10/jqueryscrollto.html

    0 讨论(0)
  • 2020-12-09 10:29
    var scrollTop = $('#contact_' + id).offset().top;
    
    $('#contact-list-scroller').attr('scrollTop', scrollTop);
    

    jsFiddle.

    0 讨论(0)
  • 2020-12-09 10:30

    I think you'll need position().top. Because the values returned by position() are relative to its parent (unlike offset()), it makes your code more flexible. If you change the position of your parent container your code won't break.

    Example:

    var contactTopPosition = $("#contact_8967").position().top;
    $("#contact-list-scroller").scrollTop(contactTopPosition);
    

    or animated:

    $("#contact-list-scroller").animate({scrollTop: contactTopPosition});
    

    See jsfiddle: http://jsfiddle.net/5zf9s/

    0 讨论(0)
  • 2020-12-09 10:33

    Even I was having same situation and wanted to scroll element to top. Now, there is direct support for this behavior.

    Just use <element>.scrollIntoView(true) JavaScript method.


    Example:

    document.getElementById("yourElementId").scrollIntoView(true);


    More Info:

    Although this is experimental now, soon will get support in every browser. You could find more info on this at : MDN

    0 讨论(0)
提交回复
热议问题