如何让CSS动画作用于所有进度条?当前仅首个进度条生效
解决多进度条动画仅生效第一个的问题
问题出在你的JavaScript代码里——document.querySelector('.progress')只会选中第一个带有.progress类的容器,所以只有第一个进度条能触发动画。要让所有进度条都生效,只需要修改JS部分,选中所有进度条容器并逐个监听:
修改后的完整代码
JavaScript
const observer = new IntersectionObserver(entries => { entries.forEach(entry => { const progressBar = entry.target.querySelector('.progress-bar'); if (entry.isIntersecting) { progressBar.classList.add('progress-animation'); } else { progressBar.classList.remove('progress-animation'); } }); }); // 选中所有.progress容器并逐个监听 document.querySelectorAll('.progress').forEach(progressContainer => { observer.observe(progressContainer); });
CSS(无需修改)
@media (prefers-reduced-motion: no-preference) { .progress-animation { animation: 2s linear 0s normal none infinite running progress-bar-stripes, animate-positive 3s; -webkit-animation: 2s linear 0s normal none infinite running progress-bar-stripes, animate-positive 3s; } }
HTML(无需修改)
<h5>Excel</h5> <div class="progress"> <div class="progress-bar" role="progressbar" aria-label="Basic example" style="width: 95%;" aria-valuenow="95" aria-valuemin="0" aria-valuemax="100"> </div> </div> <h5>PowerBI</h5> <div class="progress"> <div class="progress-bar" role="progressbar" aria-label="Basic example" style="width: 85%;" aria-valuenow="90" aria-valuemin="0" aria-valuemax="100"> </div> </div>
关键改动说明
- 把
document.querySelector('.progress')换成document.querySelectorAll('.progress'),获取页面中所有进度条容器 - 用
forEach遍历每个容器,调用observer.observe()为每个容器添加交叉监听 - 每个进度条容器进入视口时,会给自身内部的
.progress-bar添加动画类,离开时移除,保证每个进度条独立触发动画
内容的提问来源于stack exchange,提问作者oezguen
相关产品推荐
相关产品推荐

