How to prevent scrolling on prepend?

后端 未结 4 1852
广开言路
广开言路 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条回答
  •  长发绾君心
    2021-01-30 14:03

    I've done it in the past by prepending the elements, then calculating their total outerheight, and setting the scrolltop to that value. Something like this:

    var $current_top_element = $('body').children().first();
    $('body').prepend(other_elements);
    
    var previous_height = 0;
    $current_top_element.prevAll().each(function() {
      previous_height += $(this).outerHeight();
    });
    
    $('body').scrollTop(previous_height);
    

    Hope this points you in the right direction.

提交回复
热议问题