如何在页面加载时清除 URL 中的标签

How to Clear Hashtag from URL on Page Load

如果我向某人发送 link http://example.com/#about 我如何才能在页面加载 http://example.com.[=14= 时清除 URL 中的主题标签和文本]

我一直在构建利用 CSS :target 属性的灯箱。我希望如此,如果有人发送或单击 link 并在 URL 上附加了主题标签和文本,该页面基本上会忽略它或在加载时从 URL 中清除它。

我认为这是一个很常见的问题,答案很简单,但 运行 在我的研究中没有涉及任何问题。我愿意接受包括 JavaScript & jQuery.

在内的答案

如果您不介意主题标签存在但为空,您可以使用:

document.location.hash = '';

无需重新加载页面即可将 http://example.com/#about 更改为 http://example.com/#,并且具有比 history.pushState 更高的向后兼容性。

您可以在确保弹出窗口或任何内容正确加载后使用它,只需按原样调用此行即可。

使用 history.pushState 不会重新加载页面或留下尾随 #:-

history.pushState('', '', window.location.pathname);

pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL.

URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.

In a sense, calling pushState() is similar to setting window.location = "#foo", in that both will also create and activate another history entry associated with the current document. But pushState() has a few advantages:

The new URL can be any URL in the same origin as the current URL. In contrast, setting window.location keeps you at the same document only if you modify only the hash.

window.location.hash = '';//remove hash text
window.location.href.replace('#', '');//remove hash
history.replaceState(null, null, window.location.href);//replace state

我无法发表评论,但为了补充 BenG 的回答,那些不希望他们的访问者在他们的历史记录中有额外步骤的人应该使用 history.replaceState(null, null, window.location.pathname).

如果您使用 pushState,您的访问者将回击并被带到您从 URL 中删除的 state/hash,这会导致整体访问者满意度降低。

编辑:此外,根据 OP 的用例,我会确保您绑定任何 popstatehashchange 函数 after 您修改了历史对象(例如任何动画 scrollTo 或诸如此类的东西)。