Hi I want to prevent users from using the enter key unless they are in a specific text a开发者_如何学JAVArea on my form . I can stop the enter button being used but how can I find out which part of my form is in focus using js ? Any help would be great , thanks
You can assign a global variable. With jquery:
$('#id-of-textarea').focus(function(){textareaIsSelected = true});
$('#id-of-textarea').blur(function(){textareaIsSelected = false});
Although the use of globals is quite discouraged, it's the fastest way and you can check for the global anywhere in your script. If you don't use jquery you can use this shortened function:
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 (from this answer):
So now it's [document.activeElement] supported in the latest release of all major browsers (IE,FF,Safari,Chrome,Opera). I'd only use the event hack as a fallback for older browsers: if(!document.activeElement) { /* add event-listeners to set document.activeElement for older browsers */ }
if you're already using jquery, maybe this would be a workable solution
$("input, select, radio, checkbox").focus(function(){focusedField = $(this)});
$("input, select, radio, checkbox").blur(function(){focusedField = null});
精彩评论