如何避免在清空window.location.hash时滚动到页面顶部



为什么下面的代码使滚动条跳转到页面顶部?

window.location.hash = '' 

是否有一种方法可以清空它而不跳转到页面顶部?

window.location.hash跟踪页面上当前的锚点位置。当您将其设置为锚点时,页面将自动转到该锚点。当你删除它时,页面将变成"空白",这是页面的顶部!

要解决这个问题,请执行以下操作:

var scrollPosition = document.documentElement.scrollTop;
window.location.hash = '';
document.documentElement.scrollTop = scrollPosition;

当我编写的代码在setInterval上监视哈希时出现错误时,我遇到了这种行为。

setInterval(function(){
  var match = hash.match(/myValue=([^&]+)/);
  window.location.hash = '';
  if (match && match.length == 2) {
    $('#myDiv').val(match[1]);
    // RUN CODE
  }
}, 250);

在Chrome中,这段代码不会导致任何问题,但在Internet Explorer和Firefox中,它将不让你滚动,因为它总是试图滚动到页面的顶部。

当然,上面的代码无论如何都是"错误的",因为只有在找到匹配时才应该清除哈希。遗憾的是,我是在Firefox中检查后才发现这个bug的。

最新更新