简体   繁体   中英

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).

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).

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? 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/

// 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.

(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. In your case, you can check the height of the div in your ajax request and then use scrollBy , like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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