简体   繁体   English

在ajax请求上保持滚动位置

[英]Keep scroll-position on ajax-request

I have an one-page website with a lot of containers. 我有一个一页的网站 ,上面有很多容器。

The content of each container is loaded via ajax (asynchron, means not every container is filled with data at the same time). 每个容器内容都通过ajax加载 (异步,这意味着并非每个容器都同时填充数据)。

The containers have a dynamic height (height: auto). 容器具有动态高度 (高度:自动)。

The website is controlled with an intelligent routing system (if you enter a specific url, the website scrolls to the given element on load). 网站由智能路由系统控制 (如果您输入特定的URL,则网站会在加载时滚动到给定的元素)。

How can I scroll to a container (for example container 5) and keep this container on the same scroll-position (should be changable by user-scrolling) while the other containers are loading? 在加载其他容器时,如何滚动到一个容器(例如,容器5)并将该容器保持在相同的滚动位置 (应通过用户滚动来更改)? If the containers have a fixed height, the whole thing works without any problems but at the moment, the scroll-position changes on every load or change of any of those containers. 如果容器具有固定的高度,则整个容器可以正常工作,但此刻,滚动位置随每次装载或其中任何一个容器的变化而变化。

Do you know a plugin or a good way to resolve this problem? 您知道插件或解决此问题的好方法吗?

Example of the problem: http://jsfiddle.net/b6sno9cv/ 问题的示例: http : //jsfiddle.net/b6sno9cv/

// Global variable to define start-container:
var initialWidgetIdx = 10;

Expected result: 预期结果:

Scroll to container 10 and stay there (scroll-position on this container), even if the other containers are not completly loaded. 滚动到容器10并停留在此处(滚动位置在此容器上),即使其他容器没有完全装入。

(Once every container is loaded (has fixed height now), the scroll works without any problem) (一旦装载了每个容器(现在已固定高度),滚动条就可以正常工作了)

You can use offsetHeight to get the height of the element. 您可以使用offsetHeight获取元素的高度。 In your case, you can check the height of the div in your ajax request and then use scrollBy , like this 在您的情况下,您可以在ajax请求中检查div的高度,然后使用scrollBy ,如下所示

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState != 4) return
        if (xmlhttp.status == 200) {
            //do some stuff you need

            var scroll_value = document.getElementById('div_that_loaded').offsetHeight();
            window.scrollBy(0,scroll_value);
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM