我想做一個Safari瀏覽器擴展,如果光標焦點不在文本字段中執行某些操作。但是,下面的代碼檢測焦點是否不在文本字段中不起作用。Javascript代碼來檢測焦點是否在文本字段
if ($(document.activeElement).attr("type") != "text"
&& $(document.activeElement).attr("type") != "textarea") {
..do something
}
我想做一個Safari瀏覽器擴展,如果光標焦點不在文本字段中執行某些操作。但是,下面的代碼檢測焦點是否不在文本字段中不起作用。Javascript代碼來檢測焦點是否在文本字段
if ($(document.activeElement).attr("type") != "text"
&& $(document.activeElement).attr("type") != "textarea") {
..do something
}
只要保持它的簡單:
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
}
您可以使用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");
});
應該將所有非活動投入的背景爲紅色。 (在Chrome 18的了)
重複:http://stackoverflow.com/questions/497094/how-do-i-find-out-which-javascript-element -has-focus – WilHall 2012-04-27 02:01:17
'textarea'不是'type'屬性值 - 它是一個標籤名稱。你可能打算檢查'document.activeElement.localName ==「textarea」'(是的,有時事情沒有jQuery更簡單)。 – 2012-04-27 06:08:17
'localName'未在IE 8或更低版本中實現。更好(與更多瀏覽器兼容)使用'tagName.toLowerCase()=='textarea'' – RobG 2012-04-27 06:34:42