如何记住页面的滚动位置

Hur*_*rkS 6 html php jquery

我正在向我的数据库提交一些数据,然后重新加载用户刚刚打开的同一页面,我想知道是否有办法记住用户刚刚打开的滚动位置?

Joo*_*nas 16

我意识到我错过了提交的重要部分,因此,我决定调整代码以在点击事件上存储cookie,而不是在滚动时存储它的原始方式.


这是一种jquery方式:

jsfiddle (/show如果要在框架外查看它,只需添加到网址的末尾)

非常重要的是,你需要jquery cookie插件.

jQuery的:

// When document is ready...
$(document).ready(function() {

    // If cookie is set, scroll to the position saved in the cookie.
    if ( $.cookie("scroll") !== null ) {
        $(document).scrollTop( $.cookie("scroll") );
    }

    // When a button is clicked...
    $('#submit').on("click", function() {

        // Set a cookie that holds the scroll position.
        $.cookie("scroll", $(document).scrollTop() );

    });

});
Run Code Online (Sandbox Code Playgroud)

这里仍然是原始答案的代码:

的jsfiddle

jQuery的:

// When document is ready...
$(document).ready(function() {

    // If cookie is set, scroll to the position saved in the cookie.
    if ( $.cookie("scroll") !== null ) {
        $(document).scrollTop( $.cookie("scroll") );
    }

    // When scrolling happens....
    $(window).on("scroll", function() {

        // Set a cookie that holds the scroll position.
        $.cookie("scroll", $(document).scrollTop() );

    });

});
Run Code Online (Sandbox Code Playgroud)

@Cody的回答让我想起了重要的事情.

我只是检查并垂直滚动到位置.