如今解决这个问题更加触手可及。这HTML5 历史 API允许我们操纵地址栏来显示当前域内的任何 URL。
function removeHash () {
history.pushState("", document.title, window.location.pathname
+ window.location.search);
}
工作演示:http://jsfiddle.net/AndyE/ycmPt/show/
这适用于 Chrome 9、Firefox 4、Safari 5、Opera 11.50and在 IE 10 中。对于不受支持的浏览器,您始终可以编写一个优雅的降级脚本,在可用的情况下使用它:
function removeHash () {
var scrollV, scrollH, loc = window.location;
if ("pushState" in history)
history.pushState("", document.title, loc.pathname + loc.search);
else {
// Prevent scrolling by storing the page's current scroll offset
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;
loc.hash = "";
// Restore the scroll offset, should be flicker free
document.body.scrollTop = scrollV;
document.body.scrollLeft = scrollH;
}
}
因此,您可以摆脱哈希符号,只是还不能在所有浏览器中实现。
Note: if you want to replace the current page in the browser history, use replaceState()
instead of pushState()
.