How to prevent scrolling on prepend?

后端 未结 4 1880
广开言路
广开言路 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 13:56

    I believe the most universal way to do this would be to simply measure the document height before and after you've modified it:

    var old_height = $(document).height();  //store document height before modifications
    var old_scroll = $(window).scrollTop(); //remember the scroll position
    
    //do anything
    $("p:first").prepend( "

    I just became first

    " ); $(document).scrollTop(old_scroll + $(document).height() - old_height); //restore "scroll position"

    That way you can really do anything without the window moving away from the content you're reading :)

提交回复
热议问题