每次动画重复时运行功能

时间:2014-07-23 22:23:53

标签: greensock tweenlite

这是一个为弹跳方块设置动画的脚本:

http://jsfiddle.net/YH9nM/18/

var count = 1,
       tM = new TimelineLite(),
       element = $('#boxy');

function log(){
    console.log('just bounced');
    element.html('I\'ve bounced: ' + count + ' times!');
    count++;
}

tM.from( element, 2, { top:'-=60px', ease: Linear.easeNone, repeat: -1, onRepeat: log() }, 0 );

但是,onRepeat选项的行为并不像我期望的那样。不是每次动画重复时触发日志功能,而是在动画第一次启动时运行一次。

它的行为与onStart选项完全相同。为什么会这样?我怎样才能计算div无数次被反弹的次数?

2 个答案:

答案 0 :(得分:2)

您在使用log定义补间时正在运行log()功能,并将log的返回值分配给onRepeat(其中是undefined,因为你没有返回任何东西)。您希望将onRepeat var分配给log函数

变化

onRepeat: log()

onRepeat: log

您可以在行动here.

中看到这一点

答案 1 :(得分:0)

帕特里克确实回答了这个问题,但是如果您希望将参数传递给您希望在onRepeat上运行的函数,那么这就是您想要做的事情:

onRepeatParams: ['as','many','parameters','as',1,true,'ly','wants'];

我还认为访问应用时间轴的元素的最有效方法是使用self关键字,如下所示:

onRepeatParams: ["{self}"];

然后在执行此操作的函数中:

$(element.target).html('I\'ve bounced: ' + count + ' times!');

这就是我在上下文中的意思:

var count = 1,
       tM = new TimelineLite(),
       element = $('#boxy');

function log(element){
    console.log('just bounced');
    $(element.target).html('I\'ve bounced: ' + count + ' times!');
    count++;
}

tM.from( element, 2, { top:'-=60px', ease: Linear.easeNone, repeat: -1, onRepeat: log, onRepeatParams: ["{self}"] }, 0 );

http://jsfiddle.net/YH9nM/23/