在Javascript中使用setInterval()更改图像

时间:2018-04-02 22:21:00

标签: javascript html setinterval

我有4个行走序列的图像,我想让图像每500毫秒更换一次,以给出动画精灵的外观。这些图像的名称为w1.png,最高为w4.png,但它只保留在第一张图像上。我做错了什么?

<!DOCTYPE html>
<html>
<head>
<title>Animation</title>
    <script>
        function Walk(){
        var x=1;
            document.getElementById("walk").src="w"+x+".png";   
            x++;
            if(x==5){
                x=1;
            }
        }
    </script>
</head>
<body onload="setInterval(Walk(), 500)">
<h1>Animation</h1>
<img id="walk" src="w1.png">
</body>    
</html>

1 个答案:

答案 0 :(得分:-1)

<!DOCTYPE html>
<html>
<head>
<title>Animation</title>
    <script>
        var x = 1, walk_elment;

        function Walk_init() { // When the page loads, this function will be called
            walk_elment = document.getElementById("walk"); // set walk_elment refers to the img element by the id "walk"
            setInterval(Walk, 500) // every 500 ms Walk function will be called
        }
        function Walk() {
            x = x == 4 ? 1 : x+1; // it's like if (x == 4) x = 1 else x++; but in simply and clean way
            walk_elment.src = "w"+x+".png"; // change the pic
        }
    </script>
</head>
<body onload="Walk_init()">
<h1>Animation</h1>
<img id="walk" src="w1.png">
</body>    
</html>