我该如何简化这个?

时间:2013-06-24 04:19:00

标签: javascript jquery

我是JS的新手,我是自学。我想知道如何简化这个?在我的脚本中,这种块重复了太多次。

$('.itemlist').on('focus', 'textarea.remarks', function (){
        $(this).animate({height: '50px'},400);});
$('.itemlist').on('blur', 'textarea.remarks', function (){
        $(this).animate({height: '15px'},400);});

干杯。

3 个答案:

答案 0 :(得分:3)

试试吧,

var height='50px';
$('.itemlist').on('focus blur', 'textarea.remarks', function (){
    $(this).animate({height: height},400);
    height=(height=='50px') ? '15px' : '50px';
});

答案 1 :(得分:3)

您也可以这样做:

$('.itemlist').on({
    focus: function(){
        $(this).animate({ height: '50px' }, 400);
    },
    blur: function(){
        $(this).animate({ height: '15px' }, 400);
    }
}, 'textarea.remarks');

不是说它更简单,但它看起来很漂亮。 :)

答案 2 :(得分:2)

可能是这样的:

$('.itemlist').on('focusin focusout', 'textarea.remarks', function(evt)
{
    var px = 0;

    if(evt.type === 'focusin') px = 50;
    if(evt.type === 'focusout') px = 15;

    $(this).animate({ height: px }, 400);

});

更新:根据以下评论中的信息,使用focusinfocusout