简体   繁体   中英

Loading content scrolling bottom

I am using the below functions to load more results when scrolling to the bottom.

Everything is working well; the only problem is that when some content is loaded, the window scrolls back to the top instead, as if to keep the same position that it had before rather than loading new results. Actually, it does not go back completely to the top, instead it goes back to the height of the first loaded result. Therefore, to see the content that was just loaded, you must scroll back to the bottom. This is where this 'cycle' will start over again...

$(window).scroll(function () {
    if ($(document).height() <= $(window).scrollTop() + $(window).height()) {
        document.getElementById("loader_bar").style.display = 'block';
        load_result();
    }
});

function load_result() {
    counter = check_counter();
    type = $("#search_type").html();
    key = $("#search_key").html();

    $("#load_result").html("<p id='loader_bar' style='width:100%; height:32px'></p>");

    var par = "key=" + key + "&type=" + type + "&counter=" + counter;

    $.ajax({
        url: "ajax/search-columns-result.php",
        success: show_result,
        data: par,
        type: "POST"        
    });

    function show_result(rs) {
        if (rs != '') {
            $("#load_result").html(rs);
            $('#loader_bar').css('display',"none");
        } 
    }
}

function check_counter() {
    if( typeof check_counter.counter == 'undefined' ) { 
        check_counter.counter = 3;
    }
    return check_counter.counter++;
}

It looks to me like each time you call show_results , you are overwriting any previous results from the auto load:

$("#load_result").html(rs);

This would cause your the elements to be removed and then the window would scroll up (because the height of the entire document is now shorter).

I think you instead want to call

$("#load_result").append(rs);

You would also need to change how you are creating/showing your loader. Instead of:

$("#load_result").html("<p id='loader_bar' style='width:100%; height:32px'></p>");

You would have a the #loader_bar in the DOM after the #load_result element, and simply toggle display: block / display: none

Demo of your code (slightly modified to get it to render, not sure what your DOM structure is like).

Demo of fix

在ajax成功之后你可以设置不同的属性滚动条。你可以在ajax调用成功/加载新内容之后设置滚动条位置,例如

window.scrollTop(0); //for auto scroll to top

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