如何包装jquery动画?

时间:2013-07-10 14:21:23

标签: javascript jquery

我正在尝试在我的应用程序中包装集中调用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");

3 个答案:

答案 0 :(得分:2)

您可以将object作为参数传递给animate方法:

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
};

答案 1 :(得分: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

答案 2 :(得分: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"]);