首页 > 解决方案 > 类中的jquery动画回调函数

问题描述

我想要一个元素的连续动画。我创建了一个类并使用了 aj 查询动画方法,如下所示

class street {
    constructor(streetLength){
        this.lineLength=0;
        this.space=0;
        this.speed=4;
        this.streetLength=streetLength;
    }
    moveLine(element){
        $(element).animate({top:'+=1px'},100,function(){
            console.log('animating');
            this.moveLine(element);
        }); 
    }
}

当我在回调中再次使用 moveLine(element) 函数继续动画时,我收到一条错误消息,指出“moveline 不是函数。

标签: javascriptjquery

解决方案


没有测试它,但“这个”上下文可能有问题,试试这个:

class street {
    constructor(streetLength){
        this.lineLength=0;
        this.space=0;
        this.speed=4;
        this.streetLength=streetLength;
    }
    moveLine(element){
        $this = this;
        $(element).animate({top:'+=1px'},100,function(){
            console.log('animating');
            $this.moveLine(element);
        }); 
    }
}

推荐阅读