如何防止滚动父元素,即使子元素不可滚动?

3

使用CSS属性ovescroll-bahavior,我们可以在内部元素到达顶部或底部时防止滚动父元素。但是当子元素中的内容太少而无法滚动时,父元素将被滚动。为了保持一致性,我希望在这种情况下不发生滚动。我该如何实现?

.child {
  height: 5em;
  width: 5em;
  margin: 1em;
  background-color: lightgrey;
  overflow-y: scroll;
  overscroll-behavior-y: contain;
}

.parent {
  height: 8em;
  overflow-y: scroll;
  border: solid;
}
<div class="parent">
  If you try to scroll the first box, the outer box should never be scrolled. But if you try to scroll the second box, the outer box is scrolled, which is undesired.
  <div class="child">
    1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10
  </div>
  <div class="child">
    1<br>2<br>3
  </div>
</div>


如果您尝试滚动第一个框,外部框不应该被滚动。但是,如果您尝试滚动第二个框,外部框会被滚动,这是不期望的行为。只是我吗?运行代码片段没有展示出这种行为吗? - Jonathan Ciapetti
1
@user_ 为了让 overscroll-behavior-ychild 中按预期工作,child 需要是可滚动的。否则,您将需要使用 JS。 - Kameron
@user_ 你到底没有观察到哪个行为? - user
@user 请不要介意我的评论,我意识到我无法回答这个问题,我的错。 - Jonathan Ciapetti
1个回答

0

如评论中所述,为使overscroll-behavior-y符合预期,需要child可滚动。一种选择是使用带有&nbsp;span元素。最后,在这个新的span上添加max-height,以生成overflow。最终导致overscroll-behavior-y按预期工作。

.child {
  max-height: 5em;
  width: 5em;
  margin: 1em;
  background-color: lightgrey;
  overflow-y: scroll;
  overscroll-behavior-y: contain;
}

.parent {
  max-height: 8em;
  overflow-y: scroll;
  border: solid;
}

span {
  display: block;
  max-height: 3.5px;
}
<div class="parent">
  If you try to scroll the first box, the outer box should never be scrolled. But if you try to scroll the second box, the outer box is scrolled, which is undesired.
  <div class="child">
    1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10
  </div>
  <div class="child">
    1<br>2<br>3<br>
    <span>&nbsp;</span>
  </div>
</div>


这只是一个权宜之计,而不是解决方案。有不必要的滚动是很麻烦的。 - user
@user 好的,正如我所提到的,这是不可能的,因为它必须具有溢出(滚动)才能使overscroll-behavior-y起作用。就像我说的那样,你必须使用JS。一个CSS解决方案是让带滚动条的始终显示滚动条,使用::-webkit-scrollbar,这样很容易看出哪些有滚动条,哪些没有。 - Kameron
@用户像这样fiddle - Kameron

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