如何判断文本框(或文本区域)当前是否聚焦?我不需要知道是哪个,只需要知道是否有一个正在聚焦(光标在其中)。我该如何使用JavaScript和jQuery实现此操作?
如何判断文本框(或文本区域)当前是否聚焦?我不需要知道是哪个,只需要知道是否有一个正在聚焦(光标在其中)。我该如何使用JavaScript和jQuery实现此操作?
既然您已经找到了 document.activeElement
,那么您可以检查它的 nodeName。
if (document.activeElement.nodeName == 'TEXTAREA' || document.activeElement.nodeName == 'INPUT') {
// ....
}
类似这样的东西。
好的,我明白了。这是我做的:
function checkFocus() {
if ($(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea") {
//Something's selected
return true;
}
}
通过检查可编辑的HTMLDivElements来扩展已接受的答案:
if (document.activeElement.nodeName == 'TEXTAREA'
|| document.activeElement.nodeName == 'INPUT'
|| (document.activeElement.nodeName == 'DIV'
&& document.activeElement.isContentEditable)) {
// …
}
$('#yourTextAreaID:focus');
$('#yourTextAreaID').focus(function(){
// do something
});
当元素获得焦点时,会执行//do something
代码。
$('textarea:focus, input:text:focus')...
- David Thomas:focus
伪选择器,API 或快速测试也不认识... - lonesomeday$('#target').focus(function() {
alert('Handler for .focus() called.');
});
也可以尝试:
alert($("*:focus").attr("id"));