简体   繁体   English

如何根据URL中的锚标记#id激活类

[英]How to activage class based on anchor tag #id in URL

A while ago I noticed a page that highlighted certain areas of the page by getting the #some_random_id from the url. 不久前,我注意到一个页面,该页面通过从URL获取#some_random_id突出显示了页面的某些区域。

for instance /mypage-destination/#codex_destination_5 would obviously drop you down to the page area in question, but then highlight the area so you don't miss it. 例如/mypage-destination/#codex_destination_5显然会将您带到相关页面区域,但是请突出显示该区域,以免您错过它。

I looked into it, and I cannot seem to find the way to extract a URL property # anchor destination. 我调查了一下,但似乎找不到提取URL属性#锚定目标的方法。

document.getElementById(window.location.hash.substring(1)).style.backgroundColor = "#aaa";

You can use window.location.hash to get the id linked in the URL(which would return #codex_destination_5 using your example). 您可以使用window.location.hash来获取URL中链接的ID(使用您的示例将返回#codex_destination_5)。 You can then use substring(1) to omit the hash symbol(#codex_destination_5 becomes codex_destination_5). 然后,您可以使用substring(1)省略哈希符号(#codex_destination_5变为codex_destination_5)。

Using this as the id would be the next logical step. 将其用作ID将是下一个逻辑步骤。

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

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