Focusing on a textarea in Webkit after jQuery height animation
I have a jQuery event handler that essentially looks like this:
$("textarea").live("focus, click", function() {
var o = $(this),
expand_height = "60px";
o.animate({height : expand_height});
}
As you can see, onfocus or onclick it is supposed to animate the expansion of the textarea from it's initial height (20px) to it's expanded height (60px). There are a couple other things it does in reality (like clearing the default value), but this is the only part giving me trouble.
In Firefox/IE, the textarea retains focus while the height animates and the user can begin typing immediately upon clicking the textarea. In Chrome/Safari, the texta开发者_如何学编程rea loses focus so the user is unable to type in the box. If you add a callback when the animation completes to focus on the box, it doesn't work. If you add a select().focus() as in the following example, it does work:
$("textarea").live("focus, click", function() {
var o = $(this),
expand_height = "60px";
o.animate({height : expand_height}, function() {
o.select().focus();
});
}
Unfortunately, when the user clicks and starts typing, the first few chars can be lost because they have to wait for the animation to complete.
Is this a bug with webkit? How can I let the animation run AND make it responsive to the user's typing right away?
try this:
$("textarea").live("focus, click", function() {
var o = $(this),
expand_height = "60px";
o.animate({height : expand_height}, function() {
o.style.display = 'block';
});
});
This is probably a (known) webkit bug. Apparently the firing of the onmouseup
event deselects the text. This problem, and a solution involving preventDefault()
, are discussed in this SO answer.
精彩评论