JS offset 动态控制元素移动


    <style>
      #box1 {
        position: relative;
        left: 50%;
        top: 100px;
        width: 100px;
        height: 100px;
        background-color: rgb(90, 224, 96);
      }
    </style>

```html
  <body>
    <div id="box1"></div>
  </body>
```javascript

  <script>
    let box = document.querySelector('#box1');
    document.addEventListener('keydown', function (e) {
      // 上移动
      if (e.keyCode === 38) {
        box.style.top = box.offsetTop - 1 + 'px';
      }
      // 下移动
      if (e.keyCode === 40) {
        box.style.top = box.offsetTop + 1 + 'px';
      }
      // 左移动
      // console.log('左', e.keyCode);
      if (e.keyCode === 37) {
        box.style.left = box.offsetLeft - 1 + 'px';
      }
      // 右移动
      if (e.keyCode === 39) {
        box.style.left = box.offsetLeft + 1 + 'px';
      }
    });
  </script>
数值为10的时候offset显示距离不是以10为步长开始移动,然而当把数值改为1的时候上下移动都会往下,左右移动都会往右移动.求解各位大神,是不是有什么机制我给漏掉了~~

relative定位是相对于父元素body内容定位(不含margin),而offsetTop是包含父元素margin来定位的,而body默认有margin,这样会导致设置left/top会有偏差,去掉body的margin就正常了

body{margin:0}
    #box1 {
        position: absolute;
        left: 50%;
        top: 100px;
        width: 100px;
        height: 100px;
        background-color: rgb(90, 224, 96);
    }

img


有帮助或启发麻烦点下【采纳该答案】,谢谢~~

#box1换成绝对定位:position: absolute;

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        #box1 {
            position: absolute;
            left: 50%;
            top: 100px;
            width: 100px;
            height: 100px;
            background-color: rgb(90, 224, 96);
        }
    </style>
</head>
<body>
    <div id="box1"></div>


<script>
    let box = document.querySelector('#box1');
    document.addEventListener('keydown', function (e) {
        console.log(" box.offsetTop:" + box.offsetTop + " box.offsetLeft:" + box.offsetLeft);
        // 上移动
        if (e.keyCode === 38) {
            console.log('上');
            box.style.top = box.offsetTop - 1 + 'px';
        }
        // 下移动
        if (e.keyCode === 40) {
            console.log('下');
            box.style.top = box.offsetTop + 1 + 'px';
        }
        // 左移动
         
        if (e.keyCode === 37) {
            console.log('左');
            box.style.left = box.offsetLeft - 1 + 'px';
        }
        // 右移动
        if (e.keyCode === 39) {
            console.log('右');
            box.style.left = box.offsetLeft + 1 + 'px';
        }
    });
</script>
</body>
</html>