[英]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.