滚动到指定区域时如何实现div颜色填充动画?过渡与关键帧尝试无效
滚动触发颜色填充动画解决方案
看起来你遇到的问题是没法在滚动到Waypoint指定区域时触发div的填充动画,大概率是因为动画的触发逻辑和CSS状态切换没配合好。我给你一套完整的实现方案,用伪元素结合过渡效果来做,既美观又容易控制:
1. 基础HTML结构
<h1 id="whoami">Scroll to me!</h1> <div class="d8"></div>
2. CSS样式(含平滑过渡动画)
.d8 { border: 1px solid black; width: 100%; height: 2.5rem; margin-left: 5rem; border-radius: 1rem; background: #FFF; /* 初始白色背景 */ position: relative; overflow: hidden; /* 隐藏超出容器的伪元素 */ } .d8::before { content: ''; position: absolute; top: 0; left: 0; height: 100%; width: 0; /* 初始宽度为0,完全隐藏 */ background-color: #e74c3c; border-radius: 1rem; transition: width 0.8s ease-in-out; /* 800ms的平滑过渡动画 */ } /* 滚动触发后添加的类,让伪元素展开到85%宽度 */ .d8.active::before { width: 85%; }
3. Waypoints JavaScript触发逻辑
$("#whoami").waypoint(function() { $('.d8').addClass('active'); // 添加active类触发动画 }, { offset: '50%' // 可选:当元素进入视口50%时触发,可根据需求调整为'bottom-in-view'等 });
为什么这样做?
- 直接修改线性渐变属性没法用
transition过渡,所以用伪元素模拟填充效果更靠谱 - 初始状态伪元素宽度为0,添加
active类后宽度过渡到85%,视觉上就是颜色从左到右填充的效果 - Waypoints的
offset参数可以灵活调整触发时机,比如想等元素完全进入视口再触发,就改成offset: 'bottom-in-view'
如果你更倾向于用关键帧动画,也可以试试这个备选方案:
备选方案:使用Keyframes关键帧动画
.d8 { border: 1px solid black; width: 100%; height: 2.5rem; margin-left: 5rem; border-radius: 1rem; background: #FFF; position: relative; overflow: hidden; } .d8::before { content: ''; position: absolute; top: 0; left: 0; height: 100%; width: 85%; background-color: #e74c3c; border-radius: 1rem; transform: translateX(-100%); /* 初始位置在容器左侧外面 */ } /* 定义从左滑入的关键帧动画 */ @keyframes slideFill { from { transform: translateX(-100%); } to { transform: translateX(0); } } /* 触发动画的类 */ .d8.active::before { animation: slideFill 0.8s ease-in-out forwards; }
JS部分和之前完全一样,添加active类即可触发动画。
最后提醒:确保你已经正确引入了jQuery和Waypoints的库,不然JS代码会失效哦!
内容的提问来源于stack exchange,提问作者Alpit Anand
相关产品推荐
相关产品推荐

