1

これらのガイドラインに従ってdivの位置を変更して、流動的に見えるようにしようとしています。

  • 一度に非常に小さな増分
  • 1秒間に何度も
  • 与えられた角度で(したがって、endpoint()のすべてのトリガー)

divの計算と移動を処理する関数「endpoint()」をテストしましたが、意図したとおりに機能します。ただし、関数を複数回実行しようとすると、機能しません。

<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;
}

どんな助けでも大歓迎です

4

1 に答える 1

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>
于 2012-08-10T06:07:11.420 に答える