Body 滚动以一种意想不到的方式移动

Body scroll moves in an unexpected way

这是视频。 https://www.youtube.com/watch?v=l8pzl53p_TQ

完整的源代码在这里。

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      background-color: darkblue;
      height: 150vh;
    }

    #container {
      margin: 100px 0 0 100px;
      padding: 10px;
      width: 400px;
      height: 400px;
      overflow-y: scroll;
      display: flex;
      flex-direction: column;
      align-items: center;
      background-color: yellow;
    }

    .item {
      width: 300px;
      height: 40px;
      background-color: red;
      margin-bottom: 10px;
      flex-shrink: 0;
    }
  </style>
</head>
<body>
<div id="container">
</div>
<script>

  setInterval(() => {
    appendNewItem();
  }, 500);

  function appendNewItem() {
    const containerDom = document.getElementById('container');
    const appendDom = document.createElement('div');
    const firstChild = containerDom.children[0];
    appendDom.className = 'item';
    containerDom.insertBefore(appendDom, firstChild);
  }
</script>
</body>
</html>

如果 body 滚动条只是略微降低以至于列表顶部不可见,根据列表动画,body 滚动条会向意外的方向移动。

我不知道为什么会这样。我不知道这个错误的原因,也不知道如何修复它。请回复

好吧,你需要 overflow-y: scroll ; 在你的容器中,因为这个项目只是一个 div 你不需要使用 display : flex;

  #container {
      margin: 100px 0 0 100px;
      padding: 10px;
      width: 400px;
      height: 400px;
      overflow-y: scroll;//this modification
      
      /* not necessary
      display: flex;
      flex-direction: column;
      align-items: center; */

      background-color: yellow;
    }
    .item {
      width: 100%;//itèll take what ever its parents width value 
      height: 40px;
      background-color: red;
      margin-bottom: 10px;
    }

可能是浏览器的错误,或者这不是错误,因为浏览器会尝试滚动视图以通知用户插入了某些内容。

'bug' 运行 在 chrome 和 firefox 上有一个 hack:

const temp = document.documentElement.scrollTop; // new line
containerDom.insertBefore(appendDom, firstChild);
document.documentElement.scrollTop = temp; // new line

codesandbox