如何找到当前关注的文本框(或textarea)?我不知道它是哪一个,我只需知道一个是否在焦点(光标在其中)。我如何用javascript和jquery做到这一点?
答案 0 :(得分:19)
由于您找到了document.activeElement
,因此可以检查其nodeName。
if (document.activeElement.nodeName == 'TEXTAREA' || document.activeElement.nodeName == 'INPUT') {
// ....
}
类似的东西。
答案 1 :(得分:6)
好的,只是搞清楚了。这是我做的:
function checkFocus() {
if ($(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea") {
//Something's selected
return true;
}
}
答案 2 :(得分:2)
$('#yourTextAreaID:focus');
无效。 :)但是
$('#yourTextAreaID').focus(function(){
// do something
});
当元素获得焦点时,将执行//do something
代码。
答案 3 :(得分:2)
通过检查可编辑的HTMLDivElements来扩展接受的答案:
if (document.activeElement.nodeName == 'TEXTAREA'
|| document.activeElement.nodeName == 'INPUT'
|| (document.activeElement.nodeName == 'DIV'
&& document.activeElement.isContentEditable)) {
// …
}
答案 4 :(得分:1)
$('#target').focus(function() {
alert('Handler for .focus() called.');
});
同时尝试:
alert($("*:focus").attr("id"));