簡體   English   中英

如何從 URL 中刪除“#”符號

[英]How to remove the "#" symbol from the URL

我有一個鏈接可以將我帶到同一頁面的另一個部分,如下所示:

<a class="nav-link" href="#about">About</a>

這把我帶到了這里:

<section class="page-section bg-primary" id="about"></section>

每當我單擊該鏈接時,搜索欄都會顯示為http://mywebsite.com/home/#about 我想要它,以便每當單擊錨鏈接時,它都會將我帶到頁面中的該部分,但我希望它不是在搜索欄中有一個哈希,而是使用/而不是# ,例如http://mywebsite.com/home/about 我怎樣才能做到這一點?

可以使用popstate事件處理程序和history.replaceState來完成。

不確定這是否一定是最好的甚至是可行的解決方案。

window.addEventListener(`popstate`, handle);

function handle(evt) {
  if (location.hash) {
    history.replaceState(null, ``, location.pathname);
  }
}

此處無法在片段中演示,因此請查看 此 stackblitz

這應該這樣做: location.origin+location.pathname

您可以偵聽哈希更改並將搜索欄的#替換為/

這是一些(獨立的)代碼:

let first = true; // so we know whether to replace or add
window.addEventListener("hashchange", () => {
    if(first)
        return (
            history.pushState(null, null, location.href.replace("#", "/")),
            first = false
        );
    const all = location.href.split("/"); // if we replaced the last one with `/`, we don't want to add on to it
    all[all.length - 1] = location.hash.slice(1); // slice(1) gets rid of the `#`
    history.pushState(null, null, all.join("/"));
});

這展示了錨鏈接的所有正常特征,當您單擊鏈接時,頁面的歷史被推送而不是被替換。 我認為這也是您從我在您的問題中可以理解的內容中想要的。

此行為是 HTML 的一部分。 在我看來,擁有哈希路由是件好事。 但我不知道你的問題。 然而。 一個簡單的解決方案是收聽錨點並在單擊后刪除#

const anchors = document.querySelectorAll(".nav-link");
anchors.forEach(a => {
  a.addEventListener("click", () => {
    console.log("remove # from: ", window.location.href)
    window.location.href.split('#')[0]
    return false;
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM