css :focus伪类选择器介绍

css :focus伪类选择器设置html元素在成为输入焦点(该对象的 事件发生)时的样式。

例如一个链接获取了焦点后可以通过按"回车"键激活链接。可以用键盘的Tab键的遍历页面中可以获取焦点的元素,可以参考HTML中的tabindex属性。如果虚线框环绕了一个链接元素,证明此链接元素获取了焦点。

注意:webkit内核浏览器会默认给:focus状态的元素加上outline的样式。

语法:

:focus { 
   style properties 
}

如:

a:focus {outline: 1px  dotted red;}
input:focus {background: yellow;}

 

css :focus实例

input元素添加focus样式:

<!DOCTYPE html>
<html>
<head>
< >CSS :focus 伪类选择器使用详解(http://www.manongjc.com/article/1322.html)</ >
<style>
input:focus
{
background-color:yellow;
}
</style>
</head>
<body>

<p>Click inside the text fields to see a yellow background:</p>
/* http://www.manongjc.com/article/1322.html */
<form>
First name: <input type=\"text\" name=\"firstname\" /><br>
Last name: <input type=\"text\" name=\"lastname\" />
</form>

<p><b>Note:</b> For :focus to work in IE8, a DOCTYPE must be declared.</p>

</body>
</html>

在线运行

收藏 打印