滚动到视图中断了溢出滚动。

6

我有一个嵌套的子容器,但是当我尝试使用 scrollIntoView 时,它会破坏父容器。我无法理解为什么会出现这种情况。请帮我解决这个问题。
请查看下面的代码或在jsfiddle上查看。

function moveToTop() {
  console.log('MOVE TO TOP::');
  const child = document.getElementById('child');
  child.scrollIntoView({
    behavior: "smooth"
  });
}
#parent {
  background-color: blue;
  padding: 10px;
  height: 500px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

#scroller {
  overflow: auto;
  padding: 10px;
  background-color: red;
  flex-grow: 1;
}

#child {
  height: 10000px;
  background-color: green;
}

body {
  overflow: hidden;
  color: #fff;
  font-weight: bold;
}

button {
  position: fixed;
  bottom: 20px;
  width: 140px;
  left: 20%;
  right: 0;
}
<div id="parent">
  PARENT
  <div id="something">Something</div>
  <div id="scroller">
    CHILD
    <div id="child">
      GRAND CHILD
      <button onclick="moveToTop()">Top</button>
    </div>
  </div>
</div>


1
什么意思是“它破坏了父容器”? - s.kuznetsov
它的意思是,当你触发一个scrollIntoView事件时,尽管溢出在子元素中,滚动条会打破进入父视图。如果你看一下jsfiddle,可能会更好地理解我想表达的意思。对于我的糟糕英语表示抱歉。 - mkamranhamid
但是我在你的代码中没有看到任何问题。scrollIntoView 的工作方式就是滚动到指定项目的顶部。一切都是正确的。您想要看到什么通用行为? - s.kuznetsov
所以我们有一个父级子级孙级。当您单击按钮时,它会进入父级。它应该只到达孙级的顶部。 - mkamranhamid
我想我理解了你的问题。在滚动后,父块会隐藏在窗口顶部-https://ibb.co/fSjKV3p。那么呢? - s.kuznetsov
显示剩余2条评论
1个回答

6
整个问题在于scrollIntoView()正在移动窗口。但是由于#parent的溢出被隐藏了,当移动窗口时,这个元素本身会被破坏。我可以建议为#parent设置position: fixed,这将解决您的问题,但可能会对布局产生伤害。
使用scroll()方法。滚动机制本身是:
scroller.scroll(0, child.offsetTop - 55);

child.offsetTop - 子元素距离其父元素顶部的偏移量;

55 - 从 #parent 顶部到 #scroller 顶部的距离。

过渡动画必须在选择器 #scroller 中使用 CSS 设置。就像这样:

#scroller {
  ...
  scroll-behavior: smooth;
}

function moveToTop() {
  console.log('MOVE TO TOP::');
  const child = document.getElementById('child');
  const scroller = document.getElementById('scroller');
  scroller.scroll(0, child.offsetTop - 55);
}
#parent {
  background-color: blue;
  padding: 10px;
  height: 500px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

#scroller {
  overflow: auto;
  padding: 10px;
  background-color: red;
  flex-grow: 1;
  scroll-behavior: smooth;
}

#child {
  height: 10000px;
  background-color: green;
}

body {
  overflow: hidden;
  color: #fff;
  font-weight: bold;
}

button {
  position: fixed;
  bottom: 20px;
  width: 140px;
  left: 20%;
  right: 0;
}
<div id="parent">
  PARENT
  <div id="something">Something</div>
  <div id="scroller">
    CHILD
    <div id="child">
      GRAND CHILD
      <button onclick="moveToTop()">Top</button>
    </div>
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接