CSS- Highlight a div when the id is linked to using an anchor?

白昼怎懂夜的黑 提交于 2019-11-27 13:24:09

问题


What I am attempting to do is to highlight a div with a certain id, when It has been referred to by an anchor on another page IE:

User clicks link href="qw.html#test", when the page is loaded, then the div with the id="test" is highlighted so that the user can see it clearly.

I'm sure that I've seen a CSS3 example where a div is highlighted if it was linked to. Or was it JavaScript?


回答1:


You need to use the :target pseudo-class:

:target {
   background-color: #ffa;
}

JS Fiddle demo.




回答2:


You can do this in JavaScript. Refer to How to get the anchor from the URL using jQuery? on how to get the anchor from URL and then it can be something simple like

document.getElementById(hash).style.backgroundColor="Yellow";



回答3:


JavaScript can be used to dynamically add/change the class of the div:

If you have:

<div id="test"></div>

Javascript function, executed by the click of the anchor:

document.getElementById("test").className += " highlighted";

Result:

<div id="test" class=" highlighted"></div>


来源:https://stackoverflow.com/questions/11142125/css-highlight-a-div-when-the-id-is-linked-to-using-an-anchor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!