如何每隔x ms移动一个元素?

时间:2017-05-27 12:03:03

标签: javascript html

我有一个元素,我想向右移动200个像素,我希望它每隔X毫秒移动一次px(如果可能的话)。

我目前的代码:

for ( var i = 0; i <= 200; i++) {
    startPos = 300;
    nextPos = startPos;
    document.getElementById('ball').style="position:absolute; right:" + nextPos + ";";
}

1 个答案:

答案 0 :(得分:1)

您可以使用 string cmdText = @"INSERT INTO Employees ( your_field_list_comma_sep) VALUES (@id, @company, @lastname, @firstname, ......)"; OleDbCommand cmd = new OleDbCommand(cmdText, conn); cmd.Parameters.Add("@id", OleDbType.Integer).Value = iD; cmd.Parameters.Add("@company", OleDbType.VarWChar).Value = kompanija; cmd.Parameters.Add("@lastname", OleDbType.VarWChar).Value = prezime; cmd.Parameters.Add("@firstname", OleDbType.VarWChar).Value = ime; .... // add all the other parameters with their name and type .... cmd.ExecuteNonQuery(); requestAnimationFrame

setTimeout

<强>的setTimeout:

for ( var i = 0; i <= 200; i++) {
        startPos = 300;
        nextPos = startPos;
        document.getElementById('ball').style="position:absolute; right:" + nextPos + ";";
    }

<强> requestAnimationFrame:

var ball = document.getElementById('ball');
ball.style.position = 'absolute';

var interval = 10; // your X MS
var distance = 0;

var ticker = setInterval(moveBall, interval); // this function will run every 10ms till the clearInterval() is called.

function moveBall() {
    if(distance < 200) {
        distance++;
        ball.style.right = 300 + distance + "px";
    } 
    else {
        clearInterval(ticker);
    }

}