为什么当我按 w a s d 时我的 <div> 不移动? [已关闭]

问题描述 投票:0回答:1

我只是想让它动起来,但我不明白为什么它不起作用。

//code.js

document.addEventListener('DOMContentLoaded', function() {
  const blockElement = document.querySelector('.block');
  let x = 0;
  let y = 0;

  function updatePosition() {
    blockElement.style.transform = `translate(${x}px, ${y}px)`;
  }

  document.addEventListener('keydown', function(event) {
    switch (event.key) {
      case 'w':
        y -= 10;
        break;
      case 'a':
        x -= 10;
        break;
      case 's':
        y += 10;
        break;
      case 'd':
        x += 10;
        break;
      default:
        return;
    }

    updatePosition();
  });
});
/* CSS styles */
*{
  margin:0;padding:0;
} 

body{
  overflow: hidden;
}

.block{
  background:#444444;
  border-radius:5px;
  border:2px solid black;
  height:50px;
  width:50px
  position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<title>g</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="block" id="block></div>
<script src="code.js"></script>
</body>
</html>

javascript html css position
1个回答
0
投票

您需要将 div 的位置设置为绝对或固定才能移动它。

最小工作示例:

const myDiv = document.getElementById("myDiv");

document.addEventListener("keydown", (e) => {
  console.log(e.key);
  const key = e.key;

  switch (key) {
    case "ArrowUp":
      myDiv.style.top = myDiv.offsetTop - 10 + "px";
      break;
    case "ArrowDown":
      myDiv.style.top = myDiv.offsetTop + 10 + "px";
      break;
    case "ArrowLeft":
      myDiv.style.left = myDiv.offsetLeft - 10 + "px";
      break;
    case "ArrowRight":
      myDiv.style.left = myDiv.offsetLeft + 10 + "px";
      break;

    default:
      break;
  }
});
#myDiv {
  position: absolute;
  background-color: black;
  width: 200px;
  aspect-ratio: 1/1;
}
<div id="myDiv"></div>

© www.soinside.com 2019 - 2024. All rights reserved.