问题
here is my code to focus on "text2display" if clicked anywhere on the form (which is in a popup). but, how if they "tab" and navigate elsewhere (e.g. browser url), how to detect that and return focus back to ""text2display"?
$("#barcode_form").click(function(){
var focusedElement = "";
$(":focus").each(function(){
focusedElement = $(this).attr("id")
});
if(focusedElement == ""){
$('#text2display').focus()
}
})
回答1:
You'll be wanting the .blur(); function. Whenever an element has "focus" and the user leaves the "focused" item, "blur" is invoked and sends an event back to the element. An example to follow.
if(focusedElement == ""){
//if our focused element is empty
$('#text2display').live('blur', function(){
//when the target loses focus, we invoke blur, the next line focuses again.
//it's also a best practice to do something like fading in the border,
$("#text2display").focus();
});
}
Also, if I may suggest, it would be a good idea to let the user know that their focus has returned to that element. The best way to do this is to do something like adding a 'red' border, then fading that border out. One way is as follows ->
if(focusedElement == ""){
//if our focused element is empty
$('#text2display').live('blur', function(){
//when the target loses focus, we invoke blur, the next line focuses again.
//it's also a best practice to do something like fading in the border,
$("#text2display").focus(function(){
$(this).animate({
//when the element has been re-focused, we'll give it a red border briefly.
borderColor: '#ff0000';
}, function(){
//once the animation completes, fade the border out
$(this).animate({ borderColor: 'transparent' }, 2000);
}
);
});
});
}
Also, because we don't want resizing issues, we need to add some CSS to our inputs
input{
border:1px solid transparent;
}
This should work well for you.
来源:https://stackoverflow.com/questions/9530347/detect-barcode-reader-input