如何抽象JQuery动画方法

How to abstract JQuery animate method

本文关键字:JQuery 动画 方法 抽象 何抽象      更新时间:2023-09-26

下面我有一个jQuery animate方法抽象的工作示例,它运行良好。但是,如果您注意到在函数ani{}中,我在DOM元素类中进行了硬编码。我想用关键字"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