循环我的功能,但不能正确地做到这一点

时间:2013-05-29 09:56:43

标签: javascript

我有一个代码,我想在循环中运行,但它只运行一次我尝试intervel但它不工作

这是代码:

var getposition = 0;
var intervalinfo ;


         function setpostion(){
             document.getElementById("join").style.position = "absolute";
             document.getElementById("join").style.left = "0px";
             document.getElementById("join").style.top = "100px"

            intervalinfo = setInterval(getanimation ,50);
             }

             function getanimation() {
                 getposition += 5;
                document.getElementById("join").style.left = getposition + "px"; 

                 if (getposition > 500) {
                    // clearInterval(intervalinfo);
                     document.getElementById("join").style.left = "0px";

                     }

                 }

    window.onload = function() {
        setTimeout(setpostion , 2000);

        }

任何帮助都是事先明确的: - )

1 个答案:

答案 0 :(得分:1)

取出window.onload

确保您的脚本位于“join”元素下方的页面上,然后使用

var getposition = 0;
var intervalinfo;


function setpostion() {
    document.getElementById("join").style.position = "absolute";
    document.getElementById("join").style.left = "0px";
    document.getElementById("join").style.top = "100px"

    intervalinfo = setInterval(getanimation, 50);
}

function getanimation() {
    getposition += 5;
    document.getElementById("join").style.left = getposition + "px";

    if (getposition > 500) {
        // clearInterval(intervalinfo);
        document.getElementById("join").style.left = "0px";

    }

}
setTimeout(setpostion, 2000);

此处示例:http://jsfiddle.net/RobH/Nm8na/

更新(尝试2):

如果你想让它继续循环,请执行以下操作:

var getposition = 0;
var intervalinfo;


function setpostion() {
    document.getElementById("join").style.position = "absolute";
    document.getElementById("join").style.left = "0px";
    document.getElementById("join").style.top = "100px"

    intervalinfo = setInterval(getanimation, 50);
}

function getanimation() {
    getposition += 5;
    document.getElementById("join").style.left = getposition + "px";

    if (getposition > 500) {
        clearInterval(intervalinfo);
        document.getElementById("join").style.left = "0px";
        getposition = 0;
        setTimeout(setpostion, 2000);
    }

}
setTimeout(setpostion, 2000);

在这里小提琴:http://jsfiddle.net/RobH/UqtAf/