2012-04-27 6 views
4

カーソルフォーカスがテキストフィールドにない場合、何かをするサファリ拡張を作成しようとしています。しかし、フォーカスがテキストフィールドにないかどうかを検出する次のコードは機能しません。フォーカスがテキストフィールドにあるかどうかを検出するJavaScriptコード

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

重複:http://stackoverflow.com/questions/497094/how-do-i-find-out-which-javascript-element -has-focus – WilHall

+0

'textarea'は' type'属性値ではなく、タグ名です。おそらく、 'document.activeElement.localName ==" textarea "'をチェックすることを意図していました(そう、時にはjQueryを使わない方が簡単です)。 –

+0

'localName'はIE 8以下で実装されていません。 'tagName.toLowerCase()== 'textarea'を使う方が良い(より多くのブラウザと互換性がある) – RobG

答えて

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 
} 
1

赤にすべての非アクティブな入力の背景を設定する必要がありますが、この

$('input[type="text"]').focus(function() { 
    alert('Focused'); 
}); 
-2
$("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"); 
}); 

をachiveするためにjqueryのを使用することができます。 (クローム18で働いていた)

関連する問題