:focus和:active有什么区别?

CSS

阳光Mandy

2020-03-24

:focus:active伪类之间有什么区别

第3236篇《:focus和:active有什么区别?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

7个回答
十三 2020.03.24

使用“焦点”将为键盘用户提供与鼠标用户悬停鼠标时相同的效果。为了在Internet Explorer中获得相同的效果,需要“活动”。

现实情况是,这些状态无法像所有用户那样正常工作。不使用所有三个选择器会为许多无法使用鼠标的纯键盘用户带来可访问性问题。我邀请您参加#nomouse挑战赛(nomouse dot org)。

十三 2020.03.24

活动是指当用户激活该点时(例如单击鼠标,如果我们使用逐个字段中的选项卡,则活动样式没有任何迹象。也许单击需要更多时间,请尝试按住该点),然后在该点已激活。尝试这个 :

<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"/>
猪猪 2020.03.24

:focus:active是两个不同的状态。

  • :focus 表示当前选择该元素以接收输入的状态,并且
  • :active 表示当元素当前被用户激活时的状态。

例如,假设我们有一个<button><button>不会有开始与任何国家。它只是存在。如果我们Tab过去给赋予“焦点” <button>,它现在进入其:focus状态。如果然后单击(或按space),则使按钮进入其(: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, where my text just turns red
</button>

编辑:jsfiddle

乐米亚 2020.03.24

有四种情况。

  1. 默认情况下,活动和焦点均处于关闭状态。
  2. 当您按Tab键浏览可聚焦元素时,它们将进入:focus(未激活)。
  3. 当你点击一个在非聚焦元素,它进入:active(无焦点)。
  4. 当你点击一个聚焦元素进入: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。 。


元素是否可聚焦是另一个问题大多数不是默认设置。但是,它是安全的假设<a><input><textarea>在默认情况下可获得焦点。

StafanTony 2020.03.24
: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

来源:CSS伪类

樱小胖Mandy 2020.03.24

焦点只能通过键盘输入来指定,但是一个元素可以通过鼠标或键盘来激活。

如果在链接上使用:focus,则样式规则仅在按下键盘上的botton时适用。

猴子蛋蛋 2020.03.24

:focus是当元素能够接受输入时-输入框中的光标或已制表到的链接。

:active是用户激活元素的时间-用户按下鼠标按钮然后释放它之间的时间。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android