blob: 2efe251bb8ebdd88ce99ec25a440f8a90062d3c9 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
---
title: ':focus-within'
slug: 'Web/CSS/:focus-within'
tags:
- ':focus-within'
- CSS
- Layout
- Pseudo-class
- 伪类
- 参考
- 选择器
translation_of: 'Web/CSS/:focus-within'
---
<div>{{CSSRef}}</div>
<p><strong><code>:focus-within</code></strong> 是一个<a href="/zh-CN/docs/Web/CSS">CSS</a> <a href="/zh-CN/docs/Web/CSS/Pseudo-classes">伪类</a> ,表示一个元素获得焦点,或,该元素的后代元素获得焦点。换句话说,元素自身或者它的某个后代匹配 {{CSSxRef(":focus")}} 伪类。(<a href="/zh-CN/docs/Web/Web_Components/Shadow_DOM">shadow DOM 树</a>中的后代也包括在内)</p>
<pre class="brush: css no-line-numbers">/* 当 <div> 的某个后代获得焦点时,匹配 <div> */
div:focus-within {
background: cyan;
}</pre>
<p>该选择器非常实用。举个通俗的例子:表单中的某个 {{htmlElement("input")}} 字段获得焦点时,整个表单的 {{HTMLElement("form")}} 元素都可被高亮。</p>
<h2 id="语法">语法</h2>
{{csssyntax}}
<h2 id="Example">Example</h2>
<p>此例子中,当表单某个文本输入框获得焦点后,表单会被设置颜色样式。</p>
<h3 id="HTML">HTML</h3>
<pre class="brush: html"><p>试试在这个表单中输入点什么。</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></pre>
<h3 id="CSS">CSS</h3>
<pre class="brush: css">form {
border: 1px solid;
color: gray;
padding: 4px;
}
form:focus-within {
background: #ff8;
color: black;
}
input {
margin: 4px;
}
</pre>
<h3 id="结果">结果</h3>
<p>{{EmbedLiveSample("Example", 500, 150)}}</p>
<h2 id="规范">规范</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">规范</th>
<th scope="col">状态</th>
<th scope="col">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName("CSS4 Selectors", "#the-focus-within-pseudo", ":focus-within")}}</td>
<td>{{Spec2("CSS4 Selectors")}}</td>
<td>Initial definition.</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("css.selectors.focus-within")}}</p>
<h2 id="参见">参见</h2>
<ul>
<li>{{CSSxRef(":focus")}}</li>
<li>{{CSSxRef(":focus-visible")}} {{Experimental_Inline}}</li>
</ul>
|