页面长度更改时保持页面位置 [英] Maintain page position while page length changes

查看:50
本文介绍了页面长度更改时保持页面位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的情况:


  • 页面长度为4000像素。

  • 用户向下滚动页面,因此在视口上方隐藏了1000像素的内容。

然后,用户点击了按钮,任意长度的内容通过页面顶部的AJAX加载,按下视口下方的按钮(以及用户正在查看的内容)。

Then, the user clicks a button, and content of arbitrary length is loaded via AJAX at the top of the page, pushing the button (and the content the user was looking at) below the viewport.

我尝试编写Javascript回调以向下滚动到用户点击按钮之前所看到的内容,但体验并非无缝(滚动 up当插入新内容,然后向后滚动向下)。

I've tried writing a Javascript callback to scroll down to the content the user was looking at before they clicked the button, but the experience is not seamless (a scroll "up" when new content is inserted, followed by a scroll back "down").

有没有办法将视口固定在用户正在查看的内容上?

Is there any way to keep the viewport fixed on the content the user was looking at?

这是一个简化的例子,但应该明白这一点。

This is a simplified example, but should get the point across.

<div style="height: 1000px; width:1000px;" id="top-div">some content above the fold</div>
<button id="button">Click Me</button>
<img src="img.jpg" alt="Some image the user was looking at when they clicked the button." />

<script>
$("button").click(function() {
    $.get('/new/content', function(response) {
        $("#top-div").before(response);
    });
});
</script>


推荐答案

看看这个小提琴:
http://jsfiddle.net/FYEYB/

这里是重要的代码:

$("button").click(function() {
  //cache the org height
  var orgHeight = $("#content").height();
  //run your ajax request.
  mockAjax(function() {
    //in the callback ajust the height
    $(window).scrollTop($(window).scrollTop() + $("#content").height() - orgHeight);
  });
});

基本上在你的ajax请求的回调中,将容器高度的差异加到它的上面以前。您可能需要添加一个检查以确保新内容确实添加到视口上方,但我会让您弄明白。

Basically in the callback of your ajax request, add the difference in the height of the container to what it was before. You will probably need to add a check to make sure the new content was indeed added above the viewport, but I'll leave you to figure that out.

这篇关于页面长度更改时保持页面位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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