Html 刷新页面并保持滚动位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17642872/
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-29 11:08:35  来源:igfitidea点击:

Refresh Page and Keep Scroll Position

javascripthtml

提问by chriswiec

Can someone show me what i'm doing wrong? I need my page to refresh after a certain period of time, but it refreshes to the top of the page, I need it to not change the page location!So this is what I have now not working is it the meta tags? Here is what I have no still doesn't refresh must be doing something wrong?

有人可以告诉我我做错了什么吗?我需要我的页面在一段时间后刷新,但它刷新到页面顶部,我需要它不更改页面位置!所以这就是我现在无法使用的元标记?这里是我有没有还是没有刷新一定是做错了什么?

Here is what I originally had...

这是我最初拥有的...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="refresh" content="72">
        <meta http-equiv="Pragma" CONTENT="no-cache">
        <meta http-equiv="Expires" CONTENT="-1">

        <style type="text/css">
        body
        { 
            background-image: url('../Images/Black-BackGround.gif');
            background-repeat: repeat;
        }
        </style>
    </head>

    <script type="text/javascript">

    function saveScrollPositions(theForm) {
        if(theForm) {
            var scrolly = typeof window.pageYOffset != 'undefined' ? window.pageYOffset
                                                   : document.documentElement.scrollTop;
            var scrollx = typeof window.pageXOffset != 'undefined' ? window.pageXOffset
                                                  : document.documentElement.scrollLeft;
            theForm.scrollx.value = scrollx;
            theForm.scrolly.value = scrolly;
        }
    }
    </script>

 <form action="enroll.php" name="enrollment" method="post" onsubmit="return saveScrollPositions (this);">
  <input type="hidden" name="scrollx" id="scrollx" value="0" />
  <input type="hidden" name="scrolly" id="scrolly" value="0" />

  <STYLE type="text/css">
   #Nav a{ position:relative; display:block; text-decoration: none; color:Black; }
   Body td{font-Family: Arial; font-size: 12px; }
  </style>

After reading some of the initial answers I've changed it to this...

在阅读了一些最初的答案后,我已将其更改为...

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<style type="text/css">
body
{ 
    background-image: url('../Images/Black-BackGround.gif');
    background-repeat: repeat;
}
</style>
</head>


<script>
function refreshPage () {
    var page_y = $( document ).scrollTop();
    window.location.href = window.location.href + '?page_y=' + page_y;
}
window.onload = function () {
    setTimeout(refreshPage, 35000);
    if ( window.location.href.indexOf('page_y') != -1 ) {
        var match = window.location.href.split('?')[1].split("&")[0].split("=");
        $('html, body').scrollTop( match[1] );
    }
}
</script>

<STYLE type="text/css">
#Nav a{ position:relative; display:block; text-decoration: none; color:black; }
Body td{font-Family: Arial; font-size: 12px; }
</style>

采纳答案by Shawn31313

UPDATE

更新

You can use document.location.reload(true)as mentioned below instead of the forced trick below.

您可以使用document.location.reload(true)下面提到的代替下面的强制技巧。

Replace your HTML with this:

用这个替换你的 HTML:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            body { 
                background-image: url('../Images/Black-BackGround.gif');
                background-repeat: repeat;
            }
            body td {
               font-Family: Arial; 
               font-size: 12px; 
            }
            #Nav a { 
                position:relative; 
                display:block; 
                text-decoration: none; 
                color:black; 
            }
        </style>
        <script type="text/javascript">
            function refreshPage () {
                var page_y = document.getElementsByTagName("body")[0].scrollTop;
                window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
            }
            window.onload = function () {
                setTimeout(refreshPage, 35000);
                if ( window.location.href.indexOf('page_y') != -1 ) {
                    var match = window.location.href.split('?')[1].split("&")[0].split("=");
                    document.getElementsByTagName("body")[0].scrollTop = match[1];
                }
            }
        </script>
    </head>
    <body><!-- BODY CONTENT HERE --></body>
</html>

回答by powtac

document.location.reload()stores the position, see in the docs.

document.location.reload()存储位置,参见文档

Add additional trueparameter to force reload, but without restoring the position.

添加附加true参数以强制重新加载,但不恢复位置。

document.location.reload(true)

MDN docs:

MDN 文档:

The forcedReload flag changes how some browsers handle the user's scroll position. Usually reload() restores the scroll position afterward, but forced mode can scroll back to the top of the page, as if window.scrollY === 0.

强制重新加载标志改变了一些浏览器处理用户滚动位置的方式。通常 reload() 之后会恢复滚动位置,但是强制模式可以滚动回页面顶部,就好像 window.scrollY === 0。

回答by kkemple

If you don't want to use local storage then you could attach the y position of the page to the url and grab it with js on load and set the page offset to the get param you passed in, i.e.:

如果您不想使用本地存储,那么您可以将页面的 y 位置附加到 url 并在加载时使用 js 抓取它并将页面偏移量设置为您传入的 get 参数,即:

//code to refresh the page
var page_y = $( document ).scrollTop();
window.location.href = window.location.href + '?page_y=' + page_y;


//code to handle setting page offset on load
$(function() {
    if ( window.location.href.indexOf( 'page_y' ) != -1 ) {
        //gets the number from end of url
        var match = window.location.href.split('?')[1].match( /\d+$/ );
        var page_y = match[0];

        //sets the page offset 
        $( 'html, body' ).scrollTop( page_y );
    }
});

回答by zingle-dingle

This might be useful for refreshing also. But if you want to keep track of position on the page before you click on a same position.. The following code will help.

这也可能对刷新有用。但是,如果您想在单击同一位置之前跟踪页面上的位置.. 以下代码将有所帮助。

Also added a data-confirm for prompting the user if they really want to do that..

还添加了一个数据确认,用于提示用户是否真的想这样做..

Note: I'm using jQuery and js-cookie.jsto store cookie info.

注意:我使用 jQuery 和js-cookie.js来存储 cookie 信息。

$(document).ready(function() {
    // make all links with data-confirm prompt the user first.
    $('[data-confirm]').on("click", function (e) {
        e.preventDefault();
        var msg = $(this).data("confirm");
        if(confirm(msg)==true) {
            var url = this.href;
            if(url.length>0) window.location = url;
            return true;
        }
        return false;
    });

    // on certain links save the scroll postion.
    $('.saveScrollPostion').on("click", function (e) {
        e.preventDefault();
        var currentYOffset = window.pageYOffset;  // save current page postion.
        Cookies.set('jumpToScrollPostion', currentYOffset);
        if(!$(this).attr("data-confirm")) {  // if there is no data-confirm on this link then trigger the click. else we have issues.
            var url = this.href;
            window.location = url;
            //$(this).trigger('click');  // continue with click event.
        }
    });

    // check if we should jump to postion.
    if(Cookies.get('jumpToScrollPostion') !== "undefined") {
        var jumpTo = Cookies.get('jumpToScrollPostion');
        window.scrollTo(0, jumpTo);
        Cookies.remove('jumpToScrollPostion');  // and delete cookie so we don't jump again.
    }
});

A example of using it like this.

像这样使用它的一个例子。

<a href='gotopage.html' class='saveScrollPostion' data-confirm='Are you sure?'>Goto what the heck</a>

回答by Sanoj Dushmantha

this will do the magic

这会变魔术

    <script>
        document.addEventListener("DOMContentLoaded", function(event) { 
            var scrollpos = localStorage.getItem('scrollpos');
            if (scrollpos) window.scrollTo(0, scrollpos);
        });

        window.onbeforeunload = function(e) {
            localStorage.setItem('scrollpos', window.scrollY);
        };
    </script>

回答by Terry m

Thanks Sanoj, that worked for me.
However iOS does not support "onbeforeunload" on iPhone. Workaround for me was to set localStorage with js:

谢谢 Sanoj,这对我有用。
然而,iOS 不支持 iPhone 上的“onbeforeunload”。我的解决方法是使用 js 设置 localStorage:

<button onclick="myFunction()">Click me</button>

<script>
document.addEventListener("DOMContentLoaded", function(event) { 
            var scrollpos = localStorage.getItem('scrollpos');
            if (scrollpos) window.scrollTo(0, scrollpos);
        });
function myFunction() {
  localStorage.setItem('scrollpos', window.scrollY);
  location.reload(); 
}
</script>