:focus
:focus selector
version added: 1.6jQuery(':focus')
描述 選擇當(dāng)前獲取焦點(diǎn)的元素。
如同其他偽類選擇器(那些以":"開(kāi)始),建議:focus前面用標(biāo)記名稱或其他選擇;否則,通用選擇("*")是不言而喻的。換句話說(shuō),$(':focus')等同為$('*:focus')。如果你正在尋找當(dāng)前的焦點(diǎn)元素,$( document.activeElement )將檢索,而不必搜索整個(gè)DOM樹(shù)。
Example:
Adds the focused class to whatever element has focus
<!DOCTYPE html>
<html>
<head>
<style>
.focused {
background: #abcdef;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input tabIndex="1">
<input tabIndex="2">
<select tabIndex="3">
<option>select menu</option>
</select>
<div tabIndex="4">
a div
</div>
<script>
$("*").live("focus blur", function(e) {
var el = $(this);
setTimeout(function() {
el.toggleClass("focused", el.is(":focus"));
}, 0);
});
</script>
</body>
</html>