【发布时间】:2010-12-13 06:35:57
【问题描述】:
:focus 和 :active 伪类有什么区别?
【问题讨论】:
标签: css css-selectors pseudo-class
:focus 和 :active 伪类有什么区别?
【问题讨论】:
标签: css css-selectors pseudo-class
:focus 和:active 是两种不同的状态。
:focus表示当前选择元素接收输入时的状态,:active 表示元素当前被用户激活时的状态。例如,假设我们有一个<button>。 <button> 将没有任何状态开始。它只是存在。如果我们使用 Tab 将“焦点”赋予<button>,它现在进入其:focus 状态。如果您随后单击(或按 空格),则使按钮进入其 (:active) 状态。
在这一点上,当你点击一个元素时,你给它焦点,这也培养了:focus 和:active 相同的错觉。 它们不一样。当点击按钮时处于:focus:active状态。
一个例子:
<style type="text/css">
button { font-weight: normal; color: black; }
button:focus { color: red; }
button:active { font-weight: bold; }
</style>
<button>
When clicked, my text turns red AND bold!<br />
But not when focused only,<br />
where my text just turns red
</button>
编辑:jsfiddle
【讨论】:
document.activeElement 属性来获取焦点元素,尽管它需要在 try catch 中,因为 IE8 可能会抛出异常。请注意,旧版本的浏览器可能会以不同的方式处理 :active 和 :focus 。 function activeElement() { try { return document.activeElement; /* can get exeption in IE8 */ } catch(e) { } }
:active 状态
focus 和 active 声明的顺序无关紧要。仅当它们相互矛盾时才重要,例如color:red 和 color:blue(那么最后一个获胜)。
:active Adds a style to an element that is activated
:focus Adds a style to an element that has keyboard input focus
:hover Adds a style to an element when you mouse over it
:lang Adds a style to an element with a specific lang attribute
:link Adds a style to an unvisited link
:visited Adds a style to a visited link
【讨论】:
visited 链接在悬停或单击时不会改变样式,因为它们的“访问性”将覆盖其他伪类。 LVHFA 是大多数人在大多数情况下想要使用的顺序。不知道你为什么包含lang...
有四种情况。
:focus(未激活)。:active(没有焦点)。:active:focus(同时激活和聚焦)。例子:
<div>
I cannot be focused.
</div>
<div tabindex="0">
I am focusable.
</div>
div:focus {
background: green;
}
div:active {
color: orange;
}
div:focus:active {
font-weight: bold;
}
当页面加载时,都是案例 1。当您按下 tab 时,您将聚焦第二个 div 并看到它展示案例 2。当您单击第一个 div 时,您会看到案例 3。当您单击第二个 div 时,您见案例 4。
一个元素是否可聚焦是another question。大多数不是默认的。但是,可以肯定地假设 <a>、<input>、<textarea> 默认是可聚焦的。
【讨论】:
:active 而不是 :focus。这是我感到困惑的一件事,其他答案没有解决。
使用“焦点”将为键盘用户提供与鼠标用户悬停鼠标时相同的效果。需要“Active”才能在 Internet Explorer 中获得相同的效果。
现实情况是,这些状态并非对所有用户都适用。不使用所有三个选择器会给许多无法使用鼠标的纯键盘用户带来可访问性问题。我邀请您参加#nomouse 挑战(nomouse dot org)。
【讨论】:
Active 是当用户激活该点时(就像鼠标点击一样,如果我们从字段到字段使用选项卡,则活动样式没有任何迹象。也许点击需要更多时间,只需尝试按住该点),聚焦点激活后发生。试试这个:
<style type="text/css">
input { font-weight: normal; color: black; }
input:focus { color: green; outline: 1px solid green; }
input:active { color: red; outline: 1px solid red; }
</style>
<input type="text"/>
<input type="text"/>
【讨论】:
只能通过键盘输入来获得焦点,但元素可以通过鼠标或键盘两者来激活。
如果对链接使用 :focus,则样式规则仅适用于按下键盘上的按钮。
【讨论】:
:focus 不能那样工作。我正在输入的文本区域当前具有焦点,因为我单击了一个按钮。它也可以通过点击它来失去和恢复焦点,然后再次进入它。稍后,我将通过单击将焦点放在右侧的“添加评论”按钮上。所有这一切都无需键盘输入导致焦点。
:focus 是当元素能够接受输入时 - 输入框中的光标或已被选项卡指向的链接。
:active 是当一个元素被用户激活时——用户按下鼠标按钮然后释放它之间的时间。
【讨论】: