【问题标题】:Javascript code to detect if focus is in a text field用于检测焦点是否在文本字段中的 Javascript 代码
【发布时间】:2012-04-27 01:51:44
【问题描述】:

我正在尝试制作一个 Safari 扩展程序,如果光标焦点不在文本字段中,它会做一些事情。但是,以下用于检测焦点是否不在文本字段中的代码不起作用。

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

【问题讨论】:

  • textarea 不是 type 属性值 - 它是标签名称。您可能打算检查document.activeElement.localName == "textarea"(是的,有时没有jQuery 事情会更简单)。
  • localName 未在 IE 8 或更低版本中实现。更好(兼容更多浏览器)使用tagName.toLowerCase() == 'textarea'

标签: javascript jquery plugins safari-extension


【解决方案1】:

保持简单:

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
} 

【讨论】:

    【解决方案2】:

    你可以使用 jquery 来实现这个

    $('input[type="text"]').focus(function() {
       alert('Focused');
    });
    

    【讨论】:

      【解决方案3】:
      $("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");
      });
      

      应将所有非活动输入的背景设置为红色。 (在 Chrome 18 中工作)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-03
        • 1970-01-01
        • 1970-01-01
        • 2017-12-17
        • 2011-11-28
        相关资源
        最近更新 更多