1

I'm having quite a bit of trouble with this. Here's what I have so far:

var findPos = function(obj){
    var curLeft = 0;
    var curTop = 0;
    var arr = [];

    curLeft += obj.offsetLeft;
    curTop += obj.offsetTop;
    arr[arr.length] = {x: curLeft, y: curTop}; 
    return arr;
}

This only returns the starting position of the element passed into the function. But as the object move, I want it to store every position (x, y) in the array that is returned. Any suggestion as to how this can be done? I have tried recursion but that didn't really work out.

The element is moving using CSS @keyframes if that is relevant.

4

1 回答 1

1

@mbeckish 有正确的想法,并且由于数组是全局的,因此您不一定需要返回它 - 它将由函数更新。此外,似乎没有必要使用curLeft/curTop变量“累积” x,y 位置。偏移量应该足够了。你需要这样的东西:

var arr = [];

var findPos = function(obj){
    arr[arr.length] = {x:obj.offsetLeft, y:obj.offsetTop}; 
}

要随时间跟踪动画,您可以使用 setInterval() 或 setTimeout() 函数,如下所示:

var intRef = window.setInterval(function(){ findPos(obj) }, 100);

以上将每 100 毫秒触发一次并填充您的数组。然而,这将无限期地持续下去,直到你停止它,所以你需要某种触发器或结束时间。要关闭坐标跟踪,请使用:

window.clearInterval(intRef);
于 2013-09-05T14:15:32.560 回答