如何固定可调整大小的可视区域底部的拖动点,滚动时保持初始位置
解决方案
你可以通过拆分「定位锚点容器」和「滚动内容容器」的方式实现需求,无需使用sticky、fixed定位,也不需要额外做JS坐标计算。
改造逻辑
- 新增无overflow属性的外层容器作为定位锚点,设置
position: relative,原容器的边框、背景、尺寸等属性转移到外层容器上 - 原容器改为纯滚动内容层,仅保留
overflow: auto和内容相关样式,去掉定位属性 - 两个拖拽手柄(含伪元素)改为基于外层容器做绝对定位,位置始终和外层容器边缘绑定
完整代码示例
/* 新增外层定位容器 */ .resize-wrapper { position: relative; width: 300px; height: 100px; padding: 2vw 1.5vw; background-color: rgb(255, 245, 245); border: 2px solid rgb(255, 60, 255); border-radius: 3px; z-index: 5; user-select: none; box-sizing: border-box; } .resize-wrapper::after { content: ''; background-color: #ccc; position: absolute; bottom: 0; left: 0; width: 20px; height: 20px; cursor: nesw-resize; } /* 原外层容器改为滚动内容层 */ #styleChangeOuterTag { width: 100%; height: 100%; overflow: auto; } #anotherBox { background-color: red; position: absolute; bottom: 0; right: 0; width: 20px; height: 20px; cursor: nwse-resize; } #styleOptionDetails { border: 2px solid purple; border-radius: 3px; padding: 1vw; overflow: auto; }
<div class="resize-wrapper"> <div id="styleChangeOuterTag"> ContentContentContentContentContentContentContentContentContentContentContentContentContentContentContentContent <hr> <div id="styleOptionDetails"> t<br> Content <br> Content <br> Content <br> Content <br> Content <br> Content <br> Content <br> Content <br> Content <br> Content <br> Content <br> > </div> </div> <div id="anotherBox"></div> </div>
效果说明
- 内层内容滚动时,两个手柄始终固定在容器底部两侧,不会跟随内容产生位移,也没有sticky定位的滚动滞后问题
- 拖拽手柄调整外层
resize-wrapper尺寸时,手柄会自动跟随容器边缘移动,无需额外做坐标计算
内容的提问来源于stack exchange,提问作者Yupma
相关产品推荐
相关产品推荐

