简体   繁体   English

用于检测焦点是否在文本字段中的Javascript代码

[英]Javascript code to detect if focus is in a text field

I'm trying to make a safari extension that does something if the cursor focus isn't in a text field. 我正在尝试进行一个Safari扩展,如果光标焦点不在文本字段中,它会执行某些操作。 However the following code to detect if the focus isn't in a text field does not work. 但是,以下代码检测焦点是否不在文本字段中不起作用。

    if ($(document.activeElement).attr("type") != "text" 
       && $(document.activeElement).attr("type") != "textarea") {
          ..do something
    }

Just keep it simple: 保持简单:

var el = document.activeElement;

if (el && (el.tagName.toLowerCase() == 'input' && el.type == 'text' ||
    el.tagName.toLowerCase() == 'textarea')) {
  // focused element is a text input or textarea
} 

You can use jquery to achive this 您可以使用jquery来实现此目的

$('input[type="text"]').focus(function() {
   alert('Focused');
});
$("input[type=text]").filter(":not(:focus)").css("background","#ff0000");

$("input[type=text]").focus(function(){
    $(this).css("background","#ffffff");
});

$("input[type=text]").blur(function(){
    $(this).css("background","#ff0000");
});

Should set all the non-active inputs' background to red. 应将所有非活动输入的背景设置为红色。 (Worked in Chrome 18) (在Chrome 18中工作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM