0

我想要做的是:

你点击一个文本区域,它会扩大到 100 像素。通常它是50px。如果您在外部单击(或在文本区域中单击后触发模糊事件...),它应该回到正常的 50 像素高度。

如果您通过在文本区域中输入内容来触发更改事件,我希望能够单击提交按钮而不会触发模糊(将其移回 50 像素)。

我在正确的轨道上吗?

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);
    }
});
};

http://jsfiddle.net/khE4A/

4

1 回答 1

1

http://jsfiddle.net/khE4A/4/

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 3 次,您将绑定事件 3 次,而不是只需要 1 次。

此外,实际上导致代码损坏的部分是 typed 超出了模糊处理程序的范围。给回调一个具有特定名称的参数不会将该变量拉入范围。事实上,如果变量在以前可访问的范围内,它会屏蔽它。

另一个[迂腐]的事情:

$(function() {
    expandTextarea();
});​

函数包装是不必要的。由于expandTextarea不使用this,可以直接使用该函数:

$(expandTextarea);

无论如何,鉴于您问题中的问题描述,我相信您正在寻找的是:http: //jsfiddle.net/khE4A/2/

于 2012-04-28T08:13:24.370 回答