Javascript 页面重新加载,同时保持当前窗口位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7577897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:48:15  来源:igfitidea点击:

Javascript page reload while maintaining current window position

javascriptjquery

提问by JCm

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

如何在页面不返回顶部的情况下使用 Javascript 刷新页面。

My page refreshes using a timer but the problem is it goes back to the top every time it reloads. It should be able to retain the current position of the page as it reloads.

我的页面使用计时器刷新,但问题是每次重新加载时它都会回到顶部。它应该能够在重新加载时保留页面的当前位置。

P.S. Additional mouse events are welcome if necessary to be a part of your suggestion. I'm actually thinking of #idnameto target on refresh but my HTML elements don't have IDs, only classes.

PS 如果有必要,欢迎其他鼠标事件作为您建议的一部分。我实际上正在考虑#idname以刷新为目标,但我的 HTML 元素没有 ID,只有类。

回答by Mark Kramer

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

如果您使用 JavaScript,这段代码就可以解决问题。

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.

这是通过使用 cookie 来记住滚动位置来实现的。

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

来源:http : //www.huntingground.freeserve.co.uk/main/mainfram.htm?../scripts/cookies/scrollpos.htm

回答by maxedison

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#section2will reload the page and automatically scroll it down to the element with the id "section2".

如果页面的某些特定部分可能是初始“滚动到”点,那么您可以分配这些部分的 CSS id 并在末尾使用附加的 ID 哈希刷新页面。例如,将重新加载页面并自动将其向下滚动到 id 为“section2”的元素。window.location = http://example.com#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:

如果不是那么具体,您可以在刷新之前使用:.scrollTop()上的jQuery方法获取当前滚动位置。然后,您可以将其附加到刷新 URL,并在页面上包含 JS 以进行检查,以便在页面加载时自动滚动到正确的位置:window$(window).scrollTop()

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

必须在 DOM 准备好时运行以检查 currentScroll 哈希的 JS

$(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.

如果您不喜欢在地址栏中修改 URL 的想法(因为出于某种原因您确实想对用户隐藏您正在执行的操作),您可以将该scrollTo()值存储在 cookie 而不是 URL 中。

回答by SimonDever

You can do it using a cookie based method:

您可以使用基于 cookie 的方法来做到这一点:

<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.

仅取决于您的应用程序的要求和限制。

回答by Chango

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 ajaxor getmethods.

我建议只刷新您有兴趣更改的页面部分,使用 ajax。我的意思是,只是根据 ajax 调用的响应使用 javascript 替换内容。我会说你看看 jQuery 的ajaxget方法。

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!

干杯!