2010-08-26 71 views
1

嗨我想阻止用戶使用回車鍵,除非他們在我的表單上的特定文本區域。我可以停止正在使用的輸入按鈕,但是如何使用js來查明我的表單的哪個部分處於焦點狀態?任何幫助將是偉大的,謝謝如何找出表單中的哪個文本區域是焦點?

+0

dup? http://stackoverflow.com/questions/497094/how-do-i-find-out-which-javascript-element-has-focus – second 2010-08-26 16:11:01

回答

2

您可以分配一個全局變量。使用jQuery:

$('#id-of-textarea').focus(function(){textareaIsSelected = true}); 
$('#id-of-textarea').blur(function(){textareaIsSelected = false}); 

雖然使用全局變量是相當氣餒,這是最快的方式,你可以在腳本中任何檢查全局。如果你不使用jquery您可以使用此功能縮短:

function addEvent(a,b,c){ 
    if(a.addEventListener){a.addEventListener(b,c,null)}else{a.attachEvent("on"+b,c)} 
} 

function toggleTextareaSelected() 
{ 
    textareaIsSelected = !textareaIsSelected; 
} 

addEvent(document.getElementById('id-of-textarea'),'focus',toggleTextareaSelected); 
addEvent(document.getElementById('id-of-textarea'),'blur',toggleTextareaSelected); 

EDIT(從this答案):

所以現在它支持最新的 發佈[document.activeElement]所有主流瀏覽器 (IE,FF,Safari,Chrome,Opera)。我只 使用事件砍作爲備用的 舊的瀏覽器: 如果(!document.activeElement){/ *添加 事件監聽器設置 document.activeElement老年 瀏覽器* /}

0

如果你已經使用jQuery,也許這將是一個可行的解決方案

$("input, select, radio, checkbox").focus(function(){focusedField = $(this)}); 
$("input, select, radio, checkbox").blur(function(){focusedField = null}); 
相關問題