[英]ScrollIntoView breaks the overflow scroll
I have a nested child container and when I'm trying to scrollIntoView
it breaks the parent container.我有一个嵌套的子容器,当我尝试scrollIntoView
时,它会破坏父容器。 I'm not able to understand why it's acting like this.我不明白为什么它会这样。 Please help me out in this.请帮我解决这个问题。
Please have a look at the code below or on jsfiddle请查看下面的代码或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>
The whole problem is that scrollIntoView()
is moving the window .整个问题是scrollIntoView()
正在移动window 。 But since the #parent
overflow is hidden, when the window is moved, this element itself breaks.但是由于隐藏了#parent
溢出,所以当 window 被移动时,这个元素本身就会中断。 I could suggest setting a position: fixed
for the #parent
, which will solve your problem, but it can harm the layout in general.我建议为#parent
设置一个position: fixed
,这将解决您的问题,但它通常会损害布局。
Use the scroll()
method.使用scroll()
方法。 The scrolling mechanism itself is:滚动机制本身是:
scroller.scroll(0, child.offsetTop - 55);
child.offsetTop - top element; child.offsetTop - 顶部元素;
55 - distance from the top of the #parent
to the top #scroller
. 55 - 从#parent
顶部到顶部#scroller
的距离。
The transition animation must be set to css, in selector #scroller
.在选择器 #scroller 中,转换 animation 必须设置为#scroller
。 Like that:像那样:
#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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.