Javascript page reload while maintaining current window position

前端 未结 4 900
旧巷少年郎
旧巷少年郎 2020-12-09 06:48

How do I refresh the page using Javascript without the page returning to the top.

My page refreshes using a timer but the problem is it goes back to the top every ti

相关标签:
4条回答
  • 2020-12-09 07:06

    If you use JavaScript, this code will do the trick.

    var cookieName = "page_scroll";
    var expdays = 365;
    
    // An adaptation of Dorcht's cookie functions.
    
    function setCookie(name, value, expires, path, domain, secure) {
        if (!expires) expires = new Date();
        document.cookie = name + "=" + escape(value) + 
            ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
            ((path    == null) ? "" : "; path=" + path) +
            ((domain  == null) ? "" : "; domain=" + domain) +
            ((secure  == null) ? "" : "; secure");
    }
    
    function getCookie(name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
            var j = i + alen;
            if (document.cookie.substring(i, j) == arg) {
                return getCookieVal(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
        }
        return null;
    }
    
    function getCookieVal(offset) {
        var endstr = document.cookie.indexOf(";", offset);
        if (endstr == -1) endstr = document.cookie.length;
        return unescape(document.cookie.substring(offset, endstr));
    }
    
    function deleteCookie(name, path, domain) {
        document.cookie = name + "=" +
            ((path   == null) ? "" : "; path=" + path) +
            ((domain == null) ? "" : "; domain=" + domain) +
            "; expires=Thu, 01-Jan-00 00:00:01 GMT";
    }
    
    function saveScroll() {
        var expdate = new Date();
        expdate.setTime(expdate.getTime() + (expdays*24*60*60*1000)); // expiry date
    
        var x = document.pageXOffset || document.body.scrollLeft;
        var y = document.pageYOffset || document.body.scrollTop;
        var data = x + "_" + y;
        setCookie(cookieName, data, expdate);
    }
    
    function loadScroll() {
        var inf = getCookie(cookieName);
        if (!inf) { return; }
        var ar = inf.split("_");
        if (ar.length == 2) {
            window.scrollTo(parseInt(ar[0]), parseInt(ar[1]));
        }
    }
    

    This works by using a cookie to remember the scroll position.

    Now just add

    onload="loadScroll()" onunload="saveScroll()"
    

    to your body tag and all will be well.

    Source(s): http://www.huntingground.freeserve.co.uk/main/mainfram.htm?../scripts/cookies/scrollpos.htm

    0 讨论(0)
  • 2020-12-09 07:12

    If there is a certain set of specific sections of the page that are possible initial "scroll to" points, then you can assign those sections CSS ids and refresh the page with an appended ID hash at the end. For example, window.location = http://example.com#section2 will reload the page and automatically scroll it down to the element with the id "section2".

    If it's not that specific, you can grab the current scroll position prior to refresh using jQuery's .scrollTop() method on the window: $(window).scrollTop(). You can then append this to the refresh URL, and include JS on the page that checks for this in order to automatically scroll to the correct position upon page load:

    Grab current scroll position

    var currentScroll = $(window).scrollTop();
    window.location = 'http://example.com#' + currentScroll;
    

    JS that must run when DOM is ready in order to check for a currentScroll hash

    $(function(){
        if(window.location.hash !== ''){
            var scrollPos = parseInt(window.location.hash.substring(1),10);
            $(window).scrollTo(scrollPos);
        }
    });
    

    If you don't like the idea of modifying the URL in the address bar (because you really want to hide what you're doing from the user for some reason), you could store the scrollTo() value in a cookie instead of the URL.

    0 讨论(0)
  • 2020-12-09 07:13

    I would recommend refreshing only the part of the page you are interested in changing, using ajax. I mean, just replacing the content using javascript depending on the response of the ajax call. I would say you take a look at jQuery's ajax or get methods.

    If you can give more information about what you are trying to do maybe I can be of more assistance. Anyway, I hope this helps a little bit.

    Cheers!

    0 讨论(0)
  • 2020-12-09 07:17

    You can do it using a cookie based method:

    <html>
        <head>
            <script type="text/javascript">
                var refreshPeriod = 120; // 120 Seconds
    
                function refresh()
                {
                    document.cookie = 'scrollTop=' + filterScrollTop();
                    document.cookie = 'scrollLeft=' + filterScrollLeft();
                    document.location.reload(true);
                }
    
                function getCookie(name)
                {
                    var start = document.cookie.indexOf(name + "=");
                    var len = start + name.length + 1;
    
                    if(((!start) && (name != document.cookie.substring(0, name.length))) || start == -1)
                        return null;
    
                    var end = document.cookie.indexOf(";", len);
    
                    if(end == -1)
                        end = document.cookie.length;
    
                    return unescape(document.cookie.substring(len, end));
                }
    
                function deleteCookie(name)
                {
                    document.cookie = name + "=" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
                }
    
                function setupRefresh()
                {
                    var scrollTop = getCookie("scrollTop");
                    var scrollLeft = getCookie("scrollLeft");
    
                    if (!isNaN(scrollTop))
                    {
                        document.body.scrollTop = scrollTop;
                        document.documentElement.scrollTop = scrollTop;
                    }
    
                    if (!isNaN(scrollLeft))
                    {
                        document.body.scrollLeft = scrollLeft;
                        document.documentElement.scrollLeft = scrollLeft;
                    }
    
                    deleteCookie("scrollTop");
                    deleteCookie("scrollLeft");
    
                    setTimeout("refresh()", refreshPeriod * 1000);
                }
    
                function filterResults(win, docEl, body)
                {
                    var result = win ? win : 0;
    
                    if (docEl && (!result || (result > docEl)))
                        result = docEl;
    
                    return body && (!result || (result > body)) ? body : result;
                }
    
                // Setting the cookie for vertical position
                function filterScrollTop()
                {
                    var win = window.pageYOffset ? window.pageYOffset : 0;
                    var docEl = document.documentElement ? document.documentElement.scrollTop : 0;
                    var body = document.body ? document.body.scrollTop : 0;
                    return filterResults(win, docEl, body);
                }
    
                // Setting the cookie for horizontal position
                function filterScrollLeft()
                {
                    var win = window.pageXOffset ? window.pageXOffset : 0;
                    var docEl = document.documentElement ? document.documentElement.scrollLeft : 0;
                    var body = document.body ? document.body.scrollLeft : 0;
                    return filterResults(win, docEl, body);
                }
            </script>
        </head>
        <body onload="setupRefresh()">
            <!-- content here -->
        </body>
    </html>
    

    or you can do it with a form method:

    <html>
        <head>
            <script type="text/javascript">
                // Saves scroll position
                function scroll(value)
                {
                    var hidScroll = document.getElementById('hidScroll');
                    hidScroll.value = value.scrollTop;
                }
    
                // Moves scroll position to saved value
                function scrollMove(el)
                {
                    var hidScroll = document.getElementById('hidScroll');
                    document.getElementById(el).scrollTop = hidScroll.value;
                }
            </script>
        </head>
        <body onload="scrollMove('divScroll');" onunload="document.forms(0).submit()";>
            <form>
                <input type="text" id="hidScroll" name="a"><br />
                <div id="divScroll" onscroll="scroll(this);"
                     style="overflow:auto;height:100px;width:100px;">
                    <!-- content here -->
                </div>
            </form>
        </body>
    </html>
    

    Just depends on your application's requirements and restrictions.

    0 讨论(0)
提交回复
热议问题