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

我尝试了以下解决方案:

window.location.hash = '';

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


当前回答

下面是另一个使用href更改位置并在不滚动的情况下清除散列的解决方案。

这里解释了神奇的解决方案。规格。

const hash = window.location.hash;
history.scrollRestoration = 'manual';
window.location.href = hash;    
history.pushState('', document.title, window.location.pathname);

注意:提议的API现在是WhatWG HTML生活标准的一部分

其他回答

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

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

要删除散列,可以尝试使用此函数

function remove_hash_from_url()
{
    var uri = window.location.toString();
    if (uri.indexOf("#") > 0) {
        var clean_uri = uri.substring(0, uri.indexOf("#"));
        window.history.replaceState({}, document.title, clean_uri);
    }
}

下面是另一个使用href更改位置并在不滚动的情况下清除散列的解决方案。

这里解释了神奇的解决方案。规格。

const hash = window.location.hash;
history.scrollRestoration = 'manual';
window.location.href = hash;    
history.pushState('', document.title, window.location.pathname);

注意:提议的API现在是WhatWG HTML生活标准的一部分

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

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

我觉得这样更安全

if (window.history) {
    window.history.pushState('', document.title, window.location.href.replace(window.location.hash, ''));
} else {
    window.location.hash = '';
}