0

我想移动到一个矩形。当它到达行尾时,换行并将其放在下一行的开头。矩形没有很好的坐标来换行。有任何想法吗?这是我的功能:

<script type="text/javascript"><![CDATA[
    var rect = document.getElementById('player');
    var x = rect.getAttribute('x')*1,
        y = rect.getAttribute('y')*1;
    setInterval(move, 30);

    function move()
    {
        if (rect.getAttribute('x') < 500){
            rect.x.baseVal.value = ++x;
        }
        else if (rect.getAttribute('x') >= 500){
            rect.x.baseVal.value = x-250;
            rect.y.baseVal.value = y+250;
        }
    }
    ]]></script>

谢谢!

4

1 回答 1

1

从元素中获取值是不必要的昂贵,在您的情况下,它似乎获取或设置值为时已晚。而不是在每个循环上获取值,而是跟踪 forxy

var rect = document.getElementById('player');
var x = rect.getAttribute('x')*1,
    y = rect.getAttribute('y')*1;
var pos_x = 0, pos_y = 0;
setInterval(move, 30); 

function move(i)
{
    pos_x++;
    if (pos_x < 500){
        rect.setAttribute('x', pos_x);
    }
    else {
        pos_y +=10
        pos_x = 0;
        rect.setAttribute('x', pos_y);
        rect.setAttribute('y', pos_y);
    }
}​

http://jsfiddle.net/gMwMb/

于 2012-09-06T11:12:59.963 回答