如何将 CSS 样式添加到 HTML 中的聚焦锚点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15259631/
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-08-29 06:12:11  来源:igfitidea点击:

How to add CSS style to focused anchor in HTML

htmlcssanchor

提问by Giovanni

On page 1 there is a link which takes you to a certain point on page 2

在第 1 页上有一个链接,可将您带到第 2 页上的某个点

<a href="page2.html#position">MY TEXT HERE</a>

<a href="page2.html#position">MY TEXT HERE</a>

This takes you straight to the anchor (position) on page 2 with the following code

使用以下代码将您直接带到第 2 页上的锚点(位置)

<a name="position"> MORE TEXT HERE</a>

Now, my question is how can I change the text and background color when #position is in the URL?

现在,我的问题是当 #position 在 URL 中时如何更改文本和背景颜色?

For example: www.domainname.com/page2.html#position

例如:www.domainname.com/page2.html#position

This is the CSS I used but doesn't work:

这是我使用但不起作用的 CSS:

#position {
color:#ff0000;
background-color:#f5f36e;
}

Here is a example http://jsfiddle.net/jvtcj/2/

这是一个例子http://jsfiddle.net/jvtcj/2/

Thank you in advance!

先感谢您!

回答by David says reinstate Monica

Use the :targetselector:

使用:target选择器:

a:target, /* or simply */
:target {
    /* CSS to style the focused/target element */
}

You'd be better off using the idof a particular element to receive the focus, since named-anchors seem to have been dropped, if not deprecated entirely.

您最好使用id特定元素的 来接收焦点,因为如果不完全弃用,命名锚似乎已被删除。

References:

参考:

回答by powerbuoy

You can use the CSS3 :targetpeseudo selector: http://blog.teamtreehouse.com/stay-on-target

您可以使用 CSS3:target伪选择器:http://blog.teamtreehouse.com/stay-on-target

Also, don't use the old myth <a name="destination">...</a>, all you need is to idthe section you want to jump to, e.g. <section id="destination">...</section>

另外,不要使用旧的神话<a name="destination">...</a>,您只需要id跳到要跳转到的部分,例如<section id="destination">...</section>

回答by vector

<a href="#position2" id="position">MY TEXT HERE</a>
...
<a name="position2" id="pos2"> MORE TEXT HERE</a>

... in css:

...在CSS中:

a[name=position2]:target{     
    background-color:green;
}

回答by Ron

Try using

尝试使用

<a name="position" class="position"> MORE TEXT HERE</a>

And in CSS use

并在 CSS 中使用

.position {
color:#ff0000;
background-color:#f5f36e;
}

http://jsfiddle.net/jvtcj/4/

http://jsfiddle.net/jvtcj/4/

回答by Aliencaterpillar

Add an id to the tag.

为标签添加一个 id。

You can see how here using your example

你可以在这里看到如何使用你的例子

http://jsfiddle.net/h5NZh/

http://jsfiddle.net/h5NZh/

<a id="position" href="#position">MY TEXT HERE</a>