How to prevent scrolling on prepend?

后端 未结 4 1854
广开言路
广开言路 2021-01-30 13:45

I\'m prepending content to the top of the body. Sometimes this content can be 400-500px tall, and when something like this gets added, pushing the content down when you are read

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 14:10

    I took a slightly different approach:

    Start by getting the first element of the body (or of another element if you're pretending to an element other than the body which is what I needed), then after prepending the new set of elements, use the offset (if need to scroll relative to body) or the position (if need to scroll relative to an ancestor element) function on the original first element to get its updated coordinates and scroll to that point.

    Something like:

    var current_top_element = $('body').children().first();
    $('body').prepend(other_elements);
    
    $('body').scrollTop(current_top_element.offset().top);
    

    Or for something other than body scroll:

    var current_top_element = $('#ul-element-id li:first'); //example with a list
    $('#ul-element-id').prepend(other_elements);
    
    $('#ul-element-id').scrollTop(current_top_element.position().top);
    

    Be aware that position() returns the element's position relative to its offset parent , so make sure to set the css position attribute of your parent element as needed ( http://api.jquery.com/offsetParent/ )

    For more details refer to: http://api.jquery.com/category/offset/

提交回复
热议问题