Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

php - how to remember scroll position of page

I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.


Here's a jquery way of doing it:

jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )

Very importantly, you'll need the jquery cookie plugin.

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

    });

});


Here's still the code from the original answer:

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

    });

});

@Cody's answer reminded me of something important.

I only made it to check and scroll to the position vertically.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...