被 CSS 伪类 :active 搞糊涂了

2022-01-10 00:00:00 css-selectors css pseudo-class

我在 这里查看 CSS :active Selector.

I was looking here at CSS :active Selector.

:active 选择器样式链接到活跃页面

The :active selector styles links to active pages

这让我想到,HTML/CSS 术语中的活动页面"到底是什么...

That got me thinking, what the heck is an 'active page' in HTML/CSS terminology...

此时我去了 w3docs 第 5.11.3 节动态伪类::hover、:active 和 :focus.

At this point I went to the w3docs Section : 5.11.3 The dynamic pseudo-classes: :hover, :active, and :focus.

:active 伪类适用于一个元素被激活用户.例如,在时间之间用户按下鼠标按钮并释放它.

The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.

所以我使用了 w3shools try it pages 之一,并且编写一个示例,替换以下代码,您可以将其剪切 &粘贴并尝试.

So I used one of the w3shools try it pages and hack together an example, substituting the following code, which you can just cut & paste and try.

<html>
<head>
<style type="text/css">
:focus,:active
{
outline-offset: 10px;
outline: solid;
}
</style>
</head>

<body>
<p>Click the links to see the background color become yellow:</p>
<a href="http://www.w3schools.com">w3schools.com</a>
<a href="http://www.wikipedia.org">wikipedia.org</a>
<button type="button">Click Me!</button>
<form>
<input type="text"/>
</form>
</body>
</html>

表单域适用于:focus.但按钮或链接不适用于 :active.

The form field works for :focus. But the button or links don't work for :active.

这是为什么呢?w3schools 谈到的活动页面"有什么我不明白的地方吗?

Why is that? Is there something about 'active page' I'm not understanding that w3schools talked about.

我看到了这个 不错的提示,但我不认为它是相关的.

I saw this nice tip when Googling for it, but I don't think it's related.

推荐答案

CSS中没有活动页面"的概念.事实上,SitePoint Reference 揭穿了这一点:

There is no concept of "active page" in CSS. In fact, the SitePoint Reference debunks this by saying:

伪类不表示指向活动或当前页面的链接——这是 CSS 初学者常见的误解.

The pseudo-class does not signify a link to the active, or current, page—that’s a common misconception among CSS beginners.

规范说的是对的::active 只是设置激活元素的样式,例如单击(如给出的示例中)或以其他方式触发,以便浏览器开始导航到链接的目标.

What the spec says is right: :active simply styles elements that are activated, e.g. clicked (as in the example given) or in some other way triggered such that the browser starts navigating to the link's target.

请注意,它不仅仅适用于 <a> 元素;它可能适用于任何被点击的非表单输入元素.例如,您可以这样做:

Note that it doesn't just apply to <a> elements; it may apply to any non-form-input element that's clicked. For instance, you can do this:

p:active {
    color: red;
}

并且您点击的任何段落都会将其文本闪烁红色.

And any paragraph you click will flash its text red.

但是请注意,确切的定义和实现由浏览器决定,但一般,您可以依赖具有激活状态的 <a> 元素.

Note however that the exact definition and implementation is left up to the browser, but in general, you can rely on <a> elements having an activated state.

相关文章