Play My Simple HTML Game: Move the Blue Box
<html>
<head>
<title>Play My Simple HTML Game: Move the Blue Box</title>
</head>
<body>
<h1>My HTML Game</h1>
<div>
<p>Welcome to my HTML game! To play, click on the blue box below to move it around the screen.</p>
<div id='gamebox' style='width: 50px; height: 50px; background-color: blue;'></div>
</div>
<script>
let gamebox = document.getElementById('gamebox');
gamebox.addEventListener('mousedown', function(event) {
let shiftX = event.clientX - gamebox.getBoundingClientRect().left;
let shiftY = event.clientY - gamebox.getBoundingClientRect().top;
<pre><code> function moveAt(pageX, pageY) {
gamebox.style.left = pageX - shiftX + 'px';
gamebox.style.top = pageY - shiftY + 'px';
}
function onMouseMove(event) {
moveAt(event.pageX, event.pageY);
}
document.addEventListener('mousemove', onMouseMove);
gamebox.onmouseup = function() {
document.removeEventListener('mousemove', onMouseMove);
gamebox.onmouseup = null;
};
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lnQI 著作权归作者所有。请勿转载和采集!