我该如何简化它

How do I simplify this?

本文关键字:何简化      更新时间:2023-09-26

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

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

干杯。

您也可以这样做:

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

并不是说它更简单,但它看起来很漂亮

试试吧,

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

也许类似于:

$('.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