0

我正在尝试在我的应用程序中集中调用 jQuery .animate

    $('#' + this.elmItem).animate({"top": moveTo}, speed, function() {
        var item = scope.getItemSizeDom();
        scope.saveItemSize(item);
    }); // This works

我试图包装一个没有成功的方法,你能告诉我我做错了什么,这里有一个如何解决它的例子吗?

this.itemAnimate = function(direction, moveTo, speed) {
    $('#' + this.elmItem).animate({direction: moveTo}, speed, function() {
        var item = scope.getItemSizeDom();
        scope.saveItemSize(item);
    });// This does not work
};

this.itemAnimate("top", moveTo, "fast");
4

3 回答 3

2

您可以将对象作为参数传递给动画方法:

this.itemAnimate = function (direction, moveTo, speed) {
    var param = {};
    param[direction] = moveTo;
    $('#' + this.elmItem).animate(param, speed, function () {
        var item = scope.getItemSizeDom();
        scope.saveItemSize(item);
    }); // This does not work
};
于 2013-07-10T14:32:25.110 回答
1

您需要创建一个基本的 jQuery 插件:

$.fn.itemAnimate = function(direction, moveTo, speed) {
    var params = {};
    params[direction] = moveTo;
    $(this).animate(params, speed, function() {
         //do something here
    });
};

然后调用它:

$("whatever").itemAnimate("top", moveTo, "fast");

还有一个jsFiddle

于 2013-07-10T14:28:21.970 回答
0

一些阅读: http: //odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx

该函数不知道是什么this,因为它没有上下文。给它这样的上下文:

this.itemAnimate.apply(this, ["top", moveTo, "fast"]);

而不是

this.itemAnimate("top", moveTo, "fast");

但是,如果您this使用其他变量的别名会更好,这样它就不会在作用域链中丢失。

var my_thing = this; // be descriptive about what it is exactly.
my_thing.itemAnimate.apply(my_thing, ["top", moveTo, "fast"]);
于 2013-07-10T14:24:46.680 回答