我有URL: http://example.com#something,我如何删除#一些,而不导致页面刷新?

我尝试了以下解决方案:

window.location.hash = '';

但是,这不会从URL中删除散列符号#。


当前回答

试试下面的方法:

window.history.back(1);

其他回答

(太多的答案是多余的和过时的。)现在最好的解决方案是:

history.replaceState(null, null, ' ');

下面这个怎么样?

window.location。散列= ' '

请注意,我设置哈希到一个单一的空间,而不是一个空字符串。


将散列设置为无效锚也不会导致刷新。例如,

window.location.hash='invalidtag'

但是,我发现上面的解决方案是误导性的。这似乎表明在给定位置上有一个具有给定名称的锚,尽管没有锚。同时,使用空字符串会导致页面移到顶部,这有时是不可接受的。使用空格还可以确保当URL被复制、收藏和再次访问时,页面通常会位于顶部,空格将被忽略。

这是我在StackOverflow上的第一个答案。希望有人觉得它有用,它符合社区标准。

这也将删除尾随散列。 例如:http://test.com/123#abc -> http://test.com/123

if(window.history.pushState) {
    window.history.pushState('', '/', window.location.pathname)
} else {
    window.location.hash = '';
}

简单优雅:

history.replaceState({}, document.title, ".");  // replace / with . to keep url

根据上面给出的答案之一,用这个:

var scrollV, scrollH
var loc = window.location;
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;
if ("pushState" in history) {
    history.pushState("", document.title, loc.pathname + loc.search);

    // Restore the scroll offset
    document.body.scrollTop = scrollV;
    document.body.scrollLeft = scrollH;

} else {
    loc.hash = "";

    // Restore the scroll offset
    document.body.scrollTop = scrollV;
    document.body.scrollLeft = scrollH;
}