简体   繁体   English

如何从 URL 中删除“#”符号

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

I have a link that takes me to another section of the same page like this:我有一个链接可以将我带到同一页面的另一个部分,如下所示:

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

that takes me here:这把我带到了这里:

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

Whenever I click on the link, the search bar shows up as http://mywebsite.com/home/#about .每当我单击该链接时,搜索栏都会显示为http://mywebsite.com/home/#about I want it so that whenever an anchor link is clicked it takes me to that section in the page but instead of having a hash in the search bar I want it nice and clean with / instead of # , like http://mywebsite.com/home/about .我想要它,以便每当单击锚链接时,它都会将我带到页面中的该部分,但我希望它不是在搜索栏中有一个哈希,而是使用/而不是# ,例如http://mywebsite.com/home/about How can I achieve this?我怎样才能做到这一点?

This may be done using a popstate event handler and history.replaceState .可以使用popstate事件处理程序和history.replaceState来完成。

Not sure if this is necessarily the best or even a viable solution.不确定这是否一定是最好的甚至是可行的解决方案。

window.addEventListener(`popstate`, handle);

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

It can't be demonstrated in a snippet here, so check this stackblitz .此处无法在片段中演示,因此请查看 此 stackblitz

这应该这样做: location.origin+location.pathname

You can listen for the hash change and replace the search bar's # with a / .您可以侦听哈希更改并将搜索栏的#替换为/

Here's some (independent) code:这是一些(独立的)代码:

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("/"));
});

This exhibits all the normal traits of an anchor link, where when you click on a link the page's history is pushed instead of replaced.这展示了锚链接的所有正常特征,当您单击链接时,页面的历史被推送而不是被替换。 I think this is also what you wanted from what I could understand in your question.我认为这也是您从我在您的问题中可以理解的内容中想要的。

This behavior is part of HTML.此行为是 HTML 的一部分。 In my opinion is that good to have hash routes.在我看来,拥有哈希路由是件好事。 But i dont know your issue.但我不知道你的问题。 How ever.然而。 A simple solution would be to listen to the anchors and remove the # after clicking.一个简单的解决方案是收听锚点并在单击后删除#

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