gpt4 book ai didi

javascript - jQuery 在每个选定对象上触发函数

转载 作者:行者123 更新时间:2023-11-29 16:12:54 25 4
gpt4 key购买 nike

我试图在 javascript/jquery 中创建一个函数,为所选对象创建一个很酷的动画。问题是,当我也添加更多对象时,它的行为很奇怪。

我知道这是因为如果我也添加 4 个对象,代码将运行 4 次。我该如何更改它以便它只对所有选定的对象执行一次?

代码:

function showPress(name) {
var top = "15";
var bottom = "20";

$(name).hide();

$(name).show(150, function() {
$(name).animate( {
"margin-top": "+="+top+"px",
"margin-left": "+="+bottom+"px"
}, 150, function() {
$(name).animate({
"margin-top": "-="+top+"px",
"margin-left": "-="+bottom+"px"
});
});
});
}

showPress("h1");

TL;DR:这是怎么回事,我该如何解决? (我试过但失败了)

http://jsfiddle.net/LWRAj/

最佳答案

this改变name的内部引用:

$(name).show(150, function () {

$(this).animate({

"margin-top": "+="+top+"px",
"margin-left": "+="+bottom+"px"

}, 150, function () {

$(this).animate({

"margin-top": "-="+top+"px",
"margin-left": "-="+bottom+"px"

});
});
});

JSFiddle

关于javascript - jQuery 在每个选定对象上触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23230150/

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