【问题标题】:Refresh Page and Keep Scroll Position刷新页面并保持滚动位置
【发布时间】:2013-07-12 15:30:55
【问题描述】:

谁能告诉我我做错了什么?我需要我的页面在一段时间后刷新,但它刷新到页面顶部,我需要它不改变页面位置!所以这就是我现在没有工作的是元标记吗?这里是我没有仍然不刷新一定是做错了什么?

这是我最初拥有的......

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

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

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

【问题讨论】:

  • 尝试使用本地存储。
  • 我该怎么做你能告诉我我有什么?

标签: javascript html


【解决方案1】:

如果您不想使用本地存储,那么您可以将页面的 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 );
    }
});

【讨论】:

  • 所以保留meta标签并替换scrupt标签之间保存滚动位置的功能?
  • 添加://code to refresh the page var page_y = $( document ).scrollTop(); window.location.href = window.location.href + '?page_y=' + page_y; 用于保存功能。
  • 我编辑了代码以便它可以实际工作。 JavaScript 是面向对象的。 @kkemple 使用了一个不存在的 indexOf 函数。 match 变量也有问题。编辑必须被接受。
  • 现在我编辑它看起来像我认为你所说的那样,它在问题中看起来正确吗?
  • @kkemple 但这也匹配:?sadjsaid332 或 ?2332 ...另外,我不是指 RegExp..我在谈论 .split['?']
【解决方案2】:

更新

您可以使用下面提到的document.location.reload(true),而不是下面的强制技巧。

用这个替换你的 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>

【讨论】:

  • 在 firefox 上不起作用(scrollTop 始终为零)所以我使用了this
  • 我无法让它在 IE 11 中工作。我在正文中添加了一堆这些:&lt;a href="#"&gt;sadsad&lt;/a&gt;&lt;br&gt; 但当我点击链接时,我到达了页面顶部。
【解决方案3】:

document.location.reload()存储位置,见in the docs

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

document.location.reload(true)

MDN 文档:

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

【讨论】:

  • 现在MDN上已经提到了。
  • 它在您的答案链接到的页面上。他们称之为forcedReload
  • 文档说“在强制模式下(当参数设置为 true 时)新的 DOM 会加载 scrollTop == 0。” - 这听起来不像是保持滚动位置。我没有时间测试它,所以我可能会遗漏一些东西......
  • 我只适用于 Chrome,最新的 FF 或 Edge 都不会保持滚动位置,而是滚动到顶部
  • Internet Explorer 不保存该位置。我用了@zingle-dingle 的回答
【解决方案4】:

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

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

注意:我使用 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 href='gotopage.html' class='saveScrollPostion' data-confirm='Are you sure?'>Goto what the heck</a>

【讨论】:

  • 这个答案有点臃肿,但我还是喜欢它。我可以通过 cookie 检查和这两行来做到这一点: var currentYOffset = window.pageYOffset; // 保存当前页面位置。 Cookies.set('jumpToScrollPostion', currentYOffset);
【解决方案5】:

这会变魔术

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

【讨论】:

  • 非常好的和简单的解决方案。我做了一些改变。即使在浏览器关闭后,浏览器仍会存储这些数据。我用 sessionStorage 替换 localStorage 并在设置滚动位置后使用 sessionStorage.removeItem('scrollpos') 清除它。这确保了一旦浏览器关闭,滚动位置就会被清除。我将修改后的代码作为单独的答案发布。
  • 太棒了!我也为我的情况做了一些改变,但它对我来说非常有效!!谢谢!!!
【解决方案6】:

感谢 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>

【讨论】:

    【解决方案7】:

    我修改了 Sanoj Dushmantha 的答案以使用 sessionStorage 而不是 localStorage。然而,尽管有文档,浏览器仍然会在浏览器关闭后存储这些数据。为了解决这个问题,我将在重置后移除滚动位置。

    <script>
        document.addEventListener("DOMContentLoaded", function (event) {
            var scrollpos = sessionStorage.getItem('scrollpos');
            if (scrollpos) {
                window.scrollTo(0, scrollpos);
                sessionStorage.removeItem('scrollpos');
            }
        });
    
        window.addEventListener("beforeunload", function (e) {
            sessionStorage.setItem('scrollpos', window.scrollY);
        });
    </script>
    

    【讨论】:

    • 非常有用,谢谢!我有两个问题,在尝试保持滚动位置时,是否可以避免在每次加载/刷新时看到很少的过渡动画?另外,它会在标签之间共享吗?如何处理多个选项卡中的会话?为每个页面创建唯一的键名是否会对网络性能产生重大影响?
    【解决方案8】:

    我找到了一个非常简单的解决方案。只需在链接 HREF 标记中添加一个 ID 链接作为单独的参数

    <a class="page-link" href="{{ url_for('events.home', page=page_num) }}, #past_events">
    

    链接到我想要保持焦点的 div 的顶部。

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 2021-07-07
      • 2020-11-28
      • 1970-01-01
      • 2012-10-21
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多