如何用CSS和JavaScript实现粘性容器的平滑形态融合与分离效果?
滚动融合的圆角矩形实现方案
需求概述
实现两个带圆角的矩形容器(内含文字),页面向下滚动时相互靠近并融合为单个圆角矩形;向上滚动时再次分离;容器全程保持sticky定位固定于视口位置。
核心改进思路
放弃直接调整border-radius的方案,改用clip-path: inset()精确控制每个形状的圆角:
- 初始状态下,两个形状保持完整的圆角矩形
- 滚动过程中,逐渐将两个形状相邻的内侧圆角过渡为直角,同时移动位置让直边完全贴合
- 融合完成后,整体呈现为一个左右保留原圆角的矩形,衔接自然无突兀感
完整代码实现
HTML
<body> <div class="container"> <div class="shape" id="shape1">Shape 1</div> <div class="shape" id="shape2">Shape 2</div> </div> </body>
CSS
body { width: 90%; margin: 0 auto; padding: 20px; height: 2000px; } .container { position: sticky; top: 20px; display: flex; justify-content: space-between; width: 100%; } .shape { display: flex; justify-content: center; align-items: center; width: 100px; height: 30px; background-color: #000; color: #fff; clip-path: inset(0 round 15px); transition: all 0.3s ease-out; }
JavaScript
document.addEventListener('scroll', () => { const scrollPercent = Math.min(window.scrollY / (document.body.scrollHeight - window.innerHeight), 1); const totalGap = window.innerWidth - 2 * 100; const movement = (totalGap / 2) * scrollPercent; const shape1 = document.getElementById('shape1'); const shape2 = document.getElementById('shape2'); shape1.style.transform = `translateX(${movement}px)`; shape2.style.transform = `translateX(-${movement}px)`; const innerRadius = 15 * (1 - scrollPercent); shape1.style.clipPath = `inset(0 round 15px ${innerRadius}px ${innerRadius}px 15px)`; shape2.style.clipPath = `inset(0 round ${innerRadius}px 15px 15px ${innerRadius}px)`; });
关键细节说明
- clip-path参数控制:
inset(0 round tl tr br bl)中,tl/tr/br/bl分别对应左上、右上、右下、左下四个角的圆角半径。滚动时,shape1的右上/右下圆角逐渐变为0,shape2的左上/左下圆角逐渐变为0,实现相邻边的直边贴合。 - 移动距离计算:通过
totalGap计算初始状态下两个形状的间距,滚动时按进度平分间距移动,确保融合时完全对齐。 - 过渡动画:使用
transition: all 0.3s ease-out让位置和形状变化更平滑自然。
内容的提问来源于stack exchange,提问作者wheel58m
相关产品推荐
相关产品推荐

