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

thi*_*zy4 4 javascript jquery plugins safari-extension

我正在尝试进行一个safari扩展,如果光标焦点不在文本字段中,它会执行某些操作.但是,以下代码检测焦点是否不在文本字段中不起作用.

    if ($(document.activeElement).attr("type") != "text" 
       && $(document.activeElement).attr("type") != "textarea") {
          ..do something
    }
Run Code Online (Sandbox Code Playgroud)

Rob*_*obG 13

保持简单:

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
} 
Run Code Online (Sandbox Code Playgroud)