如何在jQuery中恢复刷新div的滚动位置? [英] How to restore scroll position of refreshed div in jQuery?

查看:162
本文介绍了如何在jQuery中恢复刷新div的滚动位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的div,它使页面在垂直和水平方向上都有滚动条。

每隔几分钟,我想要div的内容被刷新,所以我使用jquery get将div内容重新加载到div中。

问题在于我不希望用户看到的屏幕上的位置发生更改,我希望div能够重新加载,但用户应该仍然在看div中的同一个位置(这意味着div不应该回滚到(0,0)。



在将html覆盖到div中时有时会发生什么用$(#mainwrapper).html(data);, div是暂时空的,所以它缩小了,然后被重新填充,但用户现在在(0,0)



希望这是有道理的。

解决方案

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

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

每次滚动div时,保存滚动位置

  $('#yourdiv')。scroll(function(){
if($ ( '#yourdiv')。HTML()。长度) {
scroll_l = $('#yourdiv')。scrollLeft();
scroll_t = $('#yourdiv')。scrollTop();
}
});

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


$ b $

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


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.

解决方案

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);
});

这篇关于如何在jQuery中恢复刷新div的滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆