javascript CSS- 当 id 链接到使用锚点时突出显示 div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11142125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:10:48  来源:igfitidea点击:

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

javascriptcsshtmlanchorhighlight

提问by harley_woop

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:

我试图做的是突出显示具有特定 id 的 div,当它被另一个页面 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.

用户点击 link href="qw.html#test",当页面加载时,带有 的 divid="test"会突出显示,以便用户可以清楚地看到它。

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

我确定我看过一个 CSS3 示例,其中如果 div 被链接到,则会突出显示它。或者是 JavaScript?

回答by David says reinstate Monica

You need to use the :targetpseudo-class:

您需要使用:target伪类:

:target {
   background-color: #ffa;
}

JS Fiddle demo.

JS小提琴演示

回答by blearn

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

JavaScript 可用于动态添加/更改 div 的类:

If you have:

如果你有:

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

Javascript function, executed by the click of the anchor:

Javascript 函数,通过点击锚点执行:

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

Result:

结果:

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

回答by Yuriy Galanter

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

您可以在 JavaScript 中执行此操作。请参阅如何使用 jQuery 从 URL 获取锚点?关于如何从 URL 获取锚点,然后它可以是一些简单的东西

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