进入文本字段并输入一个字符。调试器显示:
$( document.activeElement ) => work, node found + attribute you can read
$(":focus").css("background-color","red") => work
$( ':focus' ) => not work, no node found
为什么呢?任何解决方案?
在API doc中,$(document.activeElement)是$(':focus')。只有性能差异。
请参阅:http://api.jquery.com/focus-selector/
谢谢!
<html>
<head>
<title>focus</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$(document).keypress(function(event) {
$(":focus").css("background-color","red"); // <-- work
var f3 = $( ':focus' ); // <-- NOT work
var attr3 = f3.attr('tabindex');
var id3 = f3.attr('id');
f3.val(id3);
var f1 = $( document.activeElement ); // <-- work
var attr1 = f1.attr('tabindex');
var id1 = f1.attr('id');
console.log(id1);
return;
});
});
</script>
</head>
<body>
<h1>test focus</h1>
<label>TextBox : </label>
<form>
<input id="textbox1" type="text" size="50" tabindex="1"/><br>
<input id="textbox2" type="text" size="50" tabindex="2"/>
</form>
</body>
</html>