简体   繁体   中英

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.

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.

I looked into it, and I cannot seem to find the way to extract a URL property # anchor destination.

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). You can then use substring(1) to omit the hash symbol(#codex_destination_5 becomes codex_destination_5).

Using this as the id would be the next logical step.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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