Browser does not remember position of page last viewed

后端 未结 4 699
南笙
南笙 2021-01-01 00:28

I have done a few searches for this issue and I have come up empty handed. I hope somebody can clarify things for me and point me in the right direction.

Pro

4条回答
  •  生来不讨喜
    2021-01-01 01:02

    You can use javascript and jquery to set the scroll position of the window and cookies to store the position to scroll to. In the javascript of the page with the search results you could have something like this:

    var COOKIE_NAME = "scrollPosition";
    $(document).ready( function() {
    
        // Check to see if the user already has the cookie set to scroll
        var scrollPosition = getCookie(COOKIE_NAME);
        if (scrollPosition.length > 0) {
            // Scroll to the position of the last link clicked
            window.scrollTo(0, parseInt(scrollPosition, 10));
        }
    
        // Attach an overriding click event for each link that has a class named "resultLink" so the
        // saveScrollPosition function can be called before the user is redirected.
        $("a.resultLink").each( function() {
            $(this).click( function() { 
                saveScrollPosition($(this));
            });
        });
    
    });
    
    // Get the offset (height from top of page) of the link element
    // and save it in a cookie.
    function saveScrollPosition(link) {
        var linkTop = link.offset().top;
        setCookie(COOKIE_NAME, linkTop, 1);
    }
    
    // Boring cookie helper function
    function getCookie(name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(name + "=");
            if (c_start != -1) {
                c_start = c_start + name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end ==- 1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    }
    // Another boring cookie helper function
    function setCookie(name, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = name + "=" + escape(value) +
            ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString());
    }
    

    This assumes your search result links have class="resultLink".

提交回复
热议问题