简体   繁体   English

单击链接后如何在url中隐藏id?

[英]How to hide id in url after link click?

If you would click on the link, you would see the id of the div in your url.如果你点击链接,你会在你的 url 中看到 div 的 id。 How is it possible to hide that?怎么可能隐藏呢?

 #one { margin-top: 100%; width: 50px; height: 50px; background-color: red; }
 <a href="#one">Link</a> <div id="one"></div>

Would be very thankful for help!将非常感谢您的帮助!

Add an event listener for hashchange , and then set the URL with window.history.pushStatehashchange添加一个事件监听hashchange ,然后用window.history.pushState设置 URL

 window.addEventListener("hashchange", () => window.history.pushState({}, "", '/'), {});
 #one { margin-top: 100%; width: 50px; height: 50px; background-color: red; }
 <a href="#one">Link</a> <div id="one"></div>

Working example here: https://hashchange-pushstate.lcherone.repl.co这里的工作示例: https : //hashchange-pushstate.lcherone.repl.co

You can listen to changes in the window's hash with您可以使用以下命令监听窗口散列中的更改

window.addEventListener("hashchange", () => {}, false);

Then update the url with然后更新网址

window.history.pushState();

So you would do所以你会做

function hashHandler() {
    const loc = window.location.hash.split('#')[1];
    window.history.pushState({}, 'Page Title', '/' + loc);
}

window.addEventListener('hashchange', hashHandler, false);

Note that it only works in Chrome / FF / IE 10+.请注意,它仅适用于 Chrome / FF / IE 10+。 You can read more about it here你可以在这里阅读更多关于它的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM