41

我正在尝试使用不同的 url 哈希重新加载当前页面,但它没有按预期工作。

(澄清我希望它如何工作:重新加载页面,然后滚动到新的哈希。)

方法#1:

window.location.hash = "#" + newhash;

仅滚动到此锚点而不重新加载页面。

方法#2:

window.location.hash = "#" + newhash;
window.location.reload(true);

有点工作,但它首先滚动到锚点,然后重新加载页面,然后再次滚动到锚点。

方法#3:

window.location.href = window.location.pathname + window.location.search + "&random=" + Math.round(Math.random()*100000) + "#" + newhash;

有效,但我宁愿不向 url 添加随机垃圾。

有更好的解决方案吗?

4

4 回答 4

34

删除您要导航到的锚点,然后使用方法#2?由于没有锚点,因此设置哈希不应滚动页面。

于 2009-10-19T16:51:59.190 回答
5

我有一个 JQuery 函数,$(document).ready()它检测到在我的情况下是否有附加到 URL 的散列,所以我保持该函数相同,然后只要检测到散列更改就使用强制重新加载:

$(window).on('hashchange',function(){ 
    window.location.reload(true); 
});

然后我的另一个功能-

$(document).ready(function() {
    var hash = window.location.hash;    
    if(hash) {
           //DO STUFF I WANT TO DO WITH HASHES
    }
});

就我而言,这对 UX 来说很好——可能对其他人不好。

于 2014-09-02T22:47:51.720 回答
2

应该期望#foo 将滚动到id 的锚点“foo”。如果您想使用方法 #1 并重新加载,这种方法可能会奏效。

if (Object.defineProperty && Object.getOwnPropertyDescriptor) { // ES5
    var hashDescriptor = Object.getOwnPropertyDescriptor(location, "hash"),
    hashSetter = hashDescriptor.set;
    hashDescriptor.set = function (hash) {
        hashSetter.call(location, hash);
        location.reload(true);
    };
    Object.defineProperty(location, "hash", hashDescriptor);
} else if (location.__lookupSetter__ && location.__defineSetter__) { // JS
    var hashSetter = location.__lookupSetter__("hash");
    location.__defineSetter__("hash", function (hash) {
        hashSetter.call(location, hash);
        location.reload(true)
    });
}
于 2009-10-19T19:27:43.570 回答
0

另一种选择是删除哈希并将其存储在会话存储中以在重新加载时检索:

var newUrl = location.href + '#myHash';
var splitUrl = newUrl.split('#');
newUrl = splitUrl[0];
if (splitUrl[1]){
    sessionStorage.savedHash = splitUrl[1];
}
location.href = newUrl;

然后在您的页面顶部,您可以使用以下代码:

var savedHash = sessionStorage.savedHash;
if (savedHash){
    delete sessionStorage.savedHash;
    location.hash = savedHash;
}
于 2017-03-16T19:28:21.580 回答