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

标签 javascript jquery jquery-animate

我已经创建了 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 documentation了解更多信息。

关于javascript - .apply() 方法不适用于 jQuery .animate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8714752/

相关文章:

JavaScript 获取图像的尺寸,而不是渲染图像的大小

javascript - 从另一个 .js 文件调用 javascript 函数

javascript - 使用 javascript 淡入/淡出播放/暂停音乐

javascript - Glitchy-Freezing - 滚动动画不流畅 - 使用 requestAnimationFrame

javascript - jQuery - 从数据库加载信息到不同的变量中?

jquery - 使用 jQuery 的高度切换动画

javascript - AngularJS:ng-repeat 使用对象数组的数组字段

javascript - 将多个键解构为同一变量名

javascript - 如何为大型且可维护的应用程序构建 angularJS 模型?

javascript - 将唯一的本地存储与域上的唯一网页绑定(bind)的最佳方式