How to restore scroll position of refreshed div in jQuery?

眉间皱痕 提交于 2019-12-10 13:25:13

问题


I have a very large div which makes the page have scrollbars vertically and horizontally.

Every few minutes, I want the div's content to be refreshed, so I use jquery get to reload the div contents into the div.

The catch is that I don't want the place on the screen that the user was looking at to be changed, I want the div to reload, but the user should still be looking at the same spot in the div (meaning the div should not scroll back to (0,0).

What sometimes happens when overwriting the html into the div with $( "#mainwrapper" ).html( data );, the div is momentarily empty, so it shrinks, and then is refilled, but the user is now at (0,0)

Hope this makes sense.


回答1:


Before you load the content into the div, save the scroll position.

var scroll_l = $('#yourdiv').scrollLeft(),
  scroll_t = $('#yourdiv').scrollTop();

Each time you scroll the div, save the position sothat scrolling while loading gets saved, too.

$('#yourdiv').scroll(function() {
  if ($('#yourdiv').html().length) {
    scroll_l = $('#yourdiv').scrollLeft();
    scroll_t = $('#yourdiv').scrollTop();
  }
});

And then, load the new content and re-apply the scroll positions:

$('#yourdiv').load('/your/url', function() {
  $('#yourdiv').scrollLeft(scroll_l);
  $('#yourdiv').scrollTop(scroll_t);
});


来源:https://stackoverflow.com/questions/26015090/how-to-restore-scroll-position-of-refreshed-div-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!