函数不会多次执行(正确)

时间:2012-08-10 05:50:45

标签: javascript dom

我正试图改变这些指导下的div的位置,使其看起来流畅:

  • 一次非常小的增量
  • 每秒多次
  • 在给定角度(因此在endpoint()中的所有trig)

我测试了我的函数“endpoint()”,它处理div的计算和移动,它按预期工作。但是,当我尝试多次执行该功能时,它不起作用。

<style type="text/css">
.ball
{
    width:20px;
    height:20px;
    border-radius:50%;
    background-color:#00c0c6;
    position:absolute;
    left:0px;
    top:0px;
}
</style>

<div id="tehBall" class="ball"></div>

<script type="text/javascript">
    endpoint(slopeInRadians); //WORKS!  (changes position of the div)
    endpoint(slopeInRadians); //DOESN'T work (doesn't change the position of the div)
    endpoint(slopeInRadians); //DOESN'T work (same as above)
</script>

这是端点函数的代码:

function endpoint(m) 
{
    var oldX = getStyle("tehBall", "left");
    var oldY = getStyle("tehBall", "top");

    var xAxis = parseInt(oldX);
    var yAxis = parseInt(oldY); 

    var dX = (Math.cos(m));
    var dY = ((0 - Math.sin(m))); 

    xAxis += dX;
    yAxis += dY;

    xAxis = xAxis.toString();
    yAxis = yAxis.toString();   

    xAxis += "px";
    yAxis += "px";

    document.getElementById('tehBall').style.left = xAxis;
    document.getElementById('tehBall').style.top = yAxis;   

}

getStyle的代码(用于端点函数):

function getStyle(id, property){
    var elem = document.getElementById(id);
    var value = window.getComputedStyle(elem,null).getPropertyValue(property);


    return value;
}

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

不要处理样式,只需将坐标存储在全局变量中,如下所示:

请记住在将值放入样式时对值进行舍入,因为并非所有(较旧的)浏览器都支持浮点值。

<script type="text/javascript">
var xAxis =0.0;
var yAxis = 0.0;
function endpoint(m) 
{
    var dX = (Math.cos(m)/* * d*/);
    var dY = ((0 - Math.sin(m))/* * d*/); 

    xAxis += dX;
    yAxis += dY;

    document.getElementById('tehBall').style.left = Math.round(xAxis) + 'px';
    document.getElementById('tehBall').style.top = Math.round(yAxis) + 'px';   

}
</script>