gpt4 book ai didi

javascript - 如何抽象 JQuery 动画方法

转载 作者:行者123 更新时间:2023-11-30 00:31:01 24 4
gpt4 key购买 nike

下面是我所做的 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

关于javascript - 如何抽象 JQuery 动画方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29482017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com