如何在jQuery中恢复刷新div的滚动位置?

dan*_*elb 6 html jquery get

我有一个非常大的div,使页面垂直和水平滚动条.

每隔几分钟,我希望刷新div的内容,所以我使用jquery get将div内容重新加载到div中.

问题是我不希望屏幕上用户正在看的地方被更改,我希望div重新加载,但是用户应该仍然看着div中的相同位置(意味着div应该不回滚到(0,0).

覆盖HTML与$("#mainwrapper").html的(数据)div时什么有时会发生;中,DIV是暂时空的,所以它收缩,然后再填充,但现在的用户是在(0,0 )

希望这是有道理的.

Ale*_*lex 12

在将内容加载到div之前,请保存滚动位置.

var scroll_l = $('#yourdiv').scrollLeft(),
  scroll_t = $('#yourdiv').scrollTop();
Run Code Online (Sandbox Code Playgroud)

每次滚动div时,保存加载保存时滚动的位置.

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

然后,加载新内​​容并重新应用滚动位置:

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