2013-11-15 24 views
0

我想找到哪個元素聚焦。爲此,我嘗試了以下方法。我如何從我的頁面找到焦點元素

我有我的網頁ID的2個文本框是field1,field2

var viewObj=Marionette.CompositeView.extend({ 
    events:{ 
     "blur #field1":"test", 
     "blur #field2":"test" 
    }, 
test:function(){ 
    console.log(document.activeElement.id); 
} 
}); 

我想要的東西,

如果從field1field2打印field2

如果從field2移動光標移動光標到field1打印field1

如果我點擊外面的任何地方,那麼我想打印其他東西。

我知道document.activeElement.id,但它不工作。

任何人都可以幫助我。

謝謝。

+0

如果沒有在控制檯中顯示出來,什麼是錯的與你的事件。 activeElement在所有瀏覽器中都能正常工作,所以這不是問題。 – adeneo

+0

你有沒有考慮過使用'onfocus'事件? – Halcyon

+0

這裏給出了很好的描述 http://stackoverflow.com/questions/11277989/how-to-get-the-focused-element-with-jquery –

回答

0

使用「document.activeElement」屬性。

但是Tis屬性只適用於接受擊鍵的thoase字段。

0

如果您正在使用JQuery:

$("body").focusin(function(event) { 
    alert(event.target.id); 
}); 

它會提醒你聚焦元素的ID。

http://jsfiddle.net/2Lchy/9/

相關問題