如何无需JavaScript实现带绝对定位的两个Div同步滚动?
问题描述
父容器内包含两个横向可滚动区块,其中一个区块为绝对定位(用于实现带圆角的包裹层),两者宽度一致。此前通过JavaScript同步两个区块的scrollLeft值实现滚动同步,但存在闪烁问题,希望找到无需JavaScript的方案,让两者像一个区块一样同步滚动。
原代码如下:
CSS
.container { width: 400px; border: 1px solid #ccc; height: 100px; overflow: auto; margin: 0 auto; position: relative; font-size: 18px; white-space: nowrap; } .head { overflow: auto; height: 40px; } .container .body { border: 2px solid #c4c; position: absolute; border-radius: 16px; right: 0; left: 0; bottom: 0; height: 50px; overflow: auto; }
HTML
<div class="container"> <div class="head"> we like it, but a person who isn't familiar with his story may have some difficulty seeing how it would be so fitting, but it's hard to ignore the similarities between this dog and cat. </div> <div class="body"> we like it, but a person who isn't familiar with his story may have some difficulty seeing how it would be so fitting, but it's hard to ignore the similarities between this dog and cat. </div> </div>
无JS同步滚动解决方案
核心思路是让父容器作为唯一的滚动容器,两个子区块不再独立滚动,而是跟随父容器的滚动同步移动,从根源上避免滚动不同步和闪烁问题。
修改后的代码:
CSS
.container { width: 400px; border: 1px solid #ccc; height: 100px; overflow-x: auto; /* 仅开启横向滚动 */ overflow-y: hidden; /* 关闭垂直滚动 */ margin: 0 auto; position: relative; font-size: 18px; white-space: nowrap; } .head { height: 40px; /* 移除overflow:auto,让内容跟随父容器滚动 */ } .container .body { border: 2px solid #c4c; position: absolute; border-radius: 16px; right: 0; left: 0; bottom: 0; height: 50px; /* 移除overflow:auto,内容跟随父容器滚动 */ }
HTML
<div class="container"> <div class="head"> we like it, but a person who isn't familiar with his story may have some difficulty seeing how it would be so fitting, but it's hard to ignore the similarities between this dog and cat. </div> <div class="body"> we like it, but a person who isn't familiar with his story may have some difficulty seeing how it would be so fitting, but it's hard to ignore the similarities between this dog and cat. </div> </div>
原理说明
- 父容器设置
overflow-x: auto和overflow-y: hidden,成为唯一的横向滚动容器,所有横向滚动操作都作用于父容器。 - 移除两个子区块的
overflow: auto属性,让它们的内容直接暴露在父容器的滚动上下文中,父容器滚动时,两个子区块的内容会同步跟随移动,完全无需JavaScript介入。 - 保留
.body的绝对定位和圆角样式,满足原有的视觉需求。
内容的提问来源于stack exchange,提问作者yung_gal
相关产品推荐
相关产品推荐

