jQuery在每个选定的对象上激发函数

jQuery fires function on every selected object

本文关键字:对象 函数 jQuery      更新时间:2023-09-26

我正试图在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