如何抽象JQuery动画方法

How to abstract JQuery animate method

下面是我对 jQuery animate 方法进行抽象的工作示例,它运行良好。但是,如果您注意到在函数 ani(){} 中,我在 DOM 元素 class 中进行了硬编码。我想用 'this' 关键字替换硬编码的 DOM 元素,以便我可以在其他地方使用它。当我尝试这样做时它不起作用,我尝试使用 bind() 进行试验,但我没有采取任何补救措施。

代码如下: https://jsfiddle.net/u28fhf77/2/


$(".item").hover(function() {

    ani("+=50", "+=50")



}, function() {

    ani("-=50", "-=50")


});


function ani(val1, val2) {
    var height = val1;
    var width = val2
    $(".item").animate({    // Hardcoded 'item' but want 'this'
        height: height,
        width: width
    }, 200);
}

通过为元素添加一个额外的参数来转换相当简单。

$(".item").hover(function () {
    ani(this, "+=50", "+=50");

}, function () {
    ani(this, "-=50", "-=50");

});


function ani(elem, val1, val2) {        
    $(elem).animate({ 
        height: val1,
        width: val2
    }, 200);
}

DEMO