我已经创建了一个打开和关闭嘴巴的pac-man动画,但我想让它在屏幕上移动。我玩过setTimeout(),我可以在屏幕上看到一个图像但不是实际的动画。我怎么能用纯JS做到这一点。
这是我的HTML
<body>
<div id="animation">
<img id="pacManImg" src="pacMan1.png" width="50" height="50" />
<img id="pacManImg" src="pacMan2.jpg" width="50" height="50" />
</div>
<button onclick="startAnimation()"> Start</button>
</body>
我正在使用这个为我的js
function startAnimation() {
var frames = document.getElementById("animation").children;
var frameCount = frames.length;
var i = 0;
setInterval(function () {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
}, 300);
}
只需使用i
来增加left
属性:
setInterval(function() {
frames[i % frameCount].style.display = "none";
frames[++i % frameCount].style.display = "block";
document.getElementById("animation").style.left = i + "px";
});
请注意,这需要CSS中的position: absolute;
。