:focus-within 是一个CSS 伪类 ,表示一个元素获得焦点,或,该元素的后代元素获得焦点。换句话说,元素自身或者它的某个后代匹配:focus伪类。(在shadow trees 中的后代也在匹配序列中)

/* 匹配<div>,当它的某个后代获得焦点 */
div:focus-within {
  background: cyan;
}

该选择器非常有用,举个通俗的例子:当用户在表单中某个<input> 域上获得焦点,会高亮整个表单。

语法

:focus-within

示例

例子中,当表单某个文本输入框获得焦点后,表单会被设置颜色样式。

HTML

<p>Try typing into this form.</p>

<form>
  <label for="given_name">Given Name:</label>
  <input id="given_name" type="text">
  <br>
  <label for="family_name">Family Name:</label>
  <input id="family_name" type="text">
</form>

CSS

form {
  border: 1px solid;
  color: gray;
  padding: 4px;
}

form:focus-within {
  background: #ff8;
  color: black;
}

input {
  margin: 4px;
}

Result

规范

Specification Status Comment
Selectors Level 4
:focus-within
Working Draft Initial definition.

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 60 未实现[1] 52.0 (52.0)[2] 未实现 47 10.1
Feature Android Webview Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 60 60 52.0 (52.0)[2] 未实现 47 10.3

[1] 该特征尚未实现, 详看 related enhancement request

[2] 在 bug 1176997中,该特征尚未实现。

参见

文档标签和贡献者

此页面的贡献者: nDos, qdlaoyao, 15207108156
最后编辑者: nDos,