I've been some testing reserching for this other question, when I noticed something very peculiar. FF4/5 fail to fire the focus
jQuery event. The other question which might be considered a duplicate was closed and accepted without a real answer.
For the question itself, I tried the following simple bit of code:
$('#target').focusout(function() {
$(this).focus();
});
It works well in Chrome and in IE, but it fail开发者_开发百科s on FF. Here's the jsFiddle for the lazy ones among us.
Can anyone explain this behavior? Or is it a known bug?
I think I ran into this before, and if I recall correctly it seemed to be some kind of reentrancy problem. My impression was that because FF is already in the process of transitioning focus, it won't let you initiate another focus transition. I believe my workaround was something like
$('#target').focusout(function() {
setTimeout(function() {
$(this).focus();
}, 0);
});
The manual says aboult .focus()
call
This method is a shortcut for .trigger('focus')
and from the .trigger()
topic
Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.
So as I understand it, the call $(this).focus();
is supposed to trigger the OnFocus event (if there is one attached to the object) but is not quaranteed to actually set/change the focused object.
This worked for me in Firefox 38. I needed to test different delay ms. Thanks to @camaleo comment.
$(document).ready(function() {
setTimeout(function() { $('#myid').focus(); }, 100);
});
The focus seems to work now in the latest Firefox without the need of the setTimeout function.
If you want to also select the input field you will have to make use of the .select() function though as document.execCommand('SelectAll'); doesn't seem to work on Firefox either.
So having the input field first focused and then selected you then can copy it or do whatever you want with it.
In my use case I required to copy the url from the input field if someone pressed on the copy button:
$(".copyURL").click(function(){
$(this).prev().focus().select();
document.execCommand("Copy",false,null);
});
I hope this could help anyone else who's searching for this problem!
精彩评论