.apply() 方法不适用于 jQuery .animate()

.apply() method doesn't work with jQuery .animate()

本文关键字:jQuery animate 适用于 方法 apply 不适用      更新时间:2023-09-26

我已经创建了一个jQuery动画的对象文字,我正在寻找一种简洁的方式来传递给animate()

不幸的是,.apply()似乎不适用于animate()所以我不得不求助于使用索引 - 我想知道为什么会这样以及如何让它与.apply()一起工作。

var animations = {
    slideLeft : function (moveLeft) {
        return [{
                left: moveLeft
            }, {
                duration: 300,
                easing: 'swingy'
        }];
    }
};
$randomEl.animate.apply(this, animations.slideLeft(100)); // doesn't work
$randomEl.animate(animations.slideLeft(100)[0], animations.slideLeft(100)[1]); // does work

您必须将正确的值传递给this apply。我假设这有效:

$randomEl.animate.apply($randomEl, animations.slideLeft(100));

如果你正常调用animate,比如$randomEl.animate(...),那么在animate里面,this会指$randomEl。因此,您必须$randomEl作为第一个参数传递给apply,而不是this所指的任何参数。

有关更多信息,请参阅 MDN 文档。

您为动画函数提供了错误的this参数。您应该传递$randomEl而不是this