Create Your Own Game with HTML: Simple Movement Example
<html>
<head>
<title>My Game</title>
</head>
<body>
<h1>My Game</h1>
<div>
<button id="up">↑</button>
<button id="down">↓</button>
<button id="left">←</button>
<button id="right">→</button>
<button id="reset">Reset</button>
</div>
<div style="width: 500px; height: 500px;">
<div id="player" style="position: relative; top: 0; left: 0; background-color: red; width: 20px; height: 20px;"></div>
</div>
<script>
var player = document.getElementById("player");
var position = { top: 0, left: 0 };
document.getElementById("up").addEventListener("click", function() {
position.top -= 10;
player.style.top = position.top + "px";
});
document.getElementById("down").addEventListener("click", function() {
position.top += 10;
player.style.top = position.top + "px";
});
document.getElementById("left").addEventListener("click", function() {
position.left -= 10;
player.style.left = position.left + "px";
});
document.getElementById("right").addEventListener("click", function() {
position.left += 10;
player.style.left = position.left + "px";
});
document.getElementById("reset").addEventListener("click", function() {
position.top = 0;
position.left = 0;
player.style.top = "0px";
player.style.left = "0px";
});
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lniZ 著作权归作者所有。请勿转载和采集!