CSS伪类 :focus表示获得焦点的元素(如表单输入)。当用户点击或触摸元素或通过键盘的 “tab” 键选择它时会被触发。

/* Selects any <input> when focused */
input:focus {
  color: red;
}

提示:此伪类仅适用于焦点元素本身。如果要选择包含焦点元素的元素,请使用:focus-within

语法

:focus

Example

HTML

<input class="red-input" value="I'll be red when focused."><br>
<input class="blue-input" value="I'll be blue when focused.">

CSS

.red-input:focus {
  background: yellow;
  color: red;
}

.blue-input:focus {
  background: yellow;
  color: blue;
}

结果

规范

Specification Status Comment
HTML Living Standard
:focus
Living Standard Defines HTML-specific semantics.
Selectors Level 4
:focus
Working Draft No change.
Selectors Level 3
:focus
Recommendation No change.
CSS Level 2 (Revision 1)
:focus
Recommendation Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
:focusChrome Full support 1Edge Full support YesFirefox Full support 1IE Full support 8Opera Full support 7Safari Full support 1WebView Android Full support 1Chrome Android ? Edge Mobile Full support YesFirefox Android Full support 4Opera Android Full support 6Safari iOS Full support 1Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown

 

参考

文档标签和贡献者

标签: 
此页面的贡献者: mdnwebdocs-bot, Ritr, zhangchen, Harvesty, Fadeoc, FredWe, Gaohaoyang
最后编辑者: mdnwebdocs-bot,