所以基本上我要做的就是:
您点击textarea,它将扩展到100px。通常它是50px。如果您单击外部(或在单击textarea后触发模糊事件...),它应该返回到正常的50px高度。
如果您通过在textarea中输入内容来触发更改事件,我希望能够单击提交按钮而不会触发模糊(将其移回50px)。
我是在正确的轨道上吗?
var expandTextarea = function() {
$('.js-textarea-slide').on('click', function(e) {
var typed = false;
$(this).change(function() {
typed = true;
});
$(this).animate({
height: '100'
}, 0);
});
$('.js-textarea-slide').blur(function(typed, e) {
if (!typed) {
alert('yo');
return false;
} else {
$(this).animate({
height: '50'
}, 0);
}
});
};
答案 0 :(得分:1)
var expandTextarea = function() {
//Note that this is in a scope such that the click, blur and change handlers can all see it
var typed = false;
$('.js-textarea-slide').on('click', function(e) {
//If you bind the change handler in here, it will be bound every time the click event
//is fired, not just once like you want it to be
$(this).animate({
height: '100'
}, 0);
}).change(function() {
typed = true;
});
//Note that I got rid of typed and e.
//If typed were included here, it would not have the value of the typed on line 4.
//Rather, it would have the value of whatever jQuery's event processing passes as the first
//parameter. In addition, it would hide the typed on line 4 from being accessible since
//they have the same name.
//Also, I got rid of the e parameter because it's not used, and in JavaScript, it's perfectly
//acceptable to have a paramter calling/definition count mismatch.
$('.js-textarea-slide').blur(function() {
if (!typed) {
$(this).animate({
height: '50'
}, 0);
}
});
};
//Since expandTextarea doesn't depend on the context it's called from, there's no need to wrap it
//in an extra function.
$(expandTextarea);
请注意,这遵循您在问题中描述的逻辑,而不是您的代码尝试执行的操作。无论如何,一些重要的变化:
每次单击textarea而不是一次时,您的更改事件将被绑定。例如,如果您单击textarea 3次,则会将事件绑定3次而不是仅需要1次。
此外,实际使代码破坏的部分是键入的部分超出了模糊处理程序的范围。给回调一个具有特定名称的参数不会将该变量拉入范围。实际上,如果变量位于先前可访问的范围内,它将掩盖它。
另一个[迂腐]的事情:
$(function() {
expandTextarea();
});
不需要功能包装。由于expandTextarea不使用this
,您可以直接使用该函数:
$(expandTextarea);
无论如何,考虑到你问题中对问题的描述,我相信你所寻找的是:http://jsfiddle.net/khE4A/2/