2012-04-27 2 views
4

커서 포커스가 텍스트 필드에없는 경우 무언가를 수행하는 사파리 확장을 만들려고합니다. 그러나 포커스가 텍스트 필드에 없는지 감지하는 다음 코드는 작동하지 않습니다.커서가 텍스트 필드에 포커스가 있는지 감지하는 자바 스크립트

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

을 (크롬 18 년 근무) :

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"); 
}); 

가 빨간색으로 모든 비활성 입력 '배경을 설정해야 실현하려 jQuery를 사용할 수 있습니다. 그냥 간단하게