切换浏览器标签/最小化时Swiper自动播放及CSS进度动画停止问题
Swiper自动播放进度动画切换标签后停止的问题及解决办法
我用CSS给Swiper实现了自动播放进度效果——分页器添加active类时,会触发一个时长和Swiper autoplay delay一致的CSS动画。正常浏览时功能没问题,但切换浏览器标签或最小化窗口后,Swiper自动播放暂停,动画也跟着停了,求解决办法。
现有实现代码
JavaScript代码
import Swiper, { Navigation, Pagination, Autoplay } from 'swiper'; const heroSwiper = new Swiper('.hero__swiper', { modules: [Navigation, Pagination, Autoplay], autoplay: { delay: 5000, waitForTransition: false, disableOnInteraction: false, }, slidesPerView: 1, speed: 800, grabCursor: true, navigation: { prevEl: '.hero__navigation-button--prev', nextEl: '.hero__navigation-button--next', }, pagination: { clickable: true, el: '.hero__swiper-pagination', renderBullet: (i, className) => { return `<button class="${className}">${(`0${i + 1}`).slice(-2)}</button>`; }, type: 'bullets', }, });
SCSS代码
&__swiper-pagination { position: absolute !important; top: auto !important; bottom: 12px !important; left: 50% !important; display: inline-flex !important; width: auto !important; transform: translateX(-50%) !important; pointer-events: none !important; .swiper-pagination-bullet { position: relative; display: inline-flex; width: auto !important; height: auto !important; margin: 0 24px 0 0 !important; color: #605647; font-size: 16px; line-height: 20px; background: none !important; border-radius: 0 !important; opacity: 1 !important; transition: 0.8s !important; pointer-events: all; &::before { position: absolute; top: 50%; left: 35px; width: 75px; height: 1px; background: rgba(#fff, 0.3); transform: translateY(-50%); visibility: hidden; opacity: 0; transition: 0.8s; content: ""; } &::after { position: absolute; top: 50%; left: 35px; width: 0; height: 1px; background: rgba(#fff, 1); transform: translateY(-50%); visibility: hidden; opacity: 0; transition: 0.8s; content: ""; } &.swiper-pagination-bullet-active { margin-right: 110px !important; color: #fff; &:last-child { margin-right: 0 !important; } &::before { visibility: visible; opacity: 1; } &::after { visibility: visible; opacity: 1; animation: pagination-progress 5s linear; } } &:last-child { margin: 0 !important; } } } @keyframes pagination-progress { 0% { width: 0; } 100% { width: 75px; } }
问题解决方案
通过监听页面可见性变化事件,在用户返回标签页时重新触发动画,离开时重置状态:
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { /* 由于Swiper在后台仍会运行,返回标签页时先移除active类再重新添加,以重启动画 */ const activeBullet = document.querySelector('.swiper-pagination-bullet-active'); if (activeBullet) { activeBullet.classList.remove('swiper-pagination-bullet-active'); } // 加10ms延迟确保CSS动画能正常启动 setTimeout(() => { document.querySelectorAll('.swiper-pagination-bullet')[heroSwiper.activeIndex].classList.add('swiper-pagination-bullet-active'); }, 10); } else { const activeBullet = document.querySelector('.swiper-pagination-bullet-active'); if (activeBullet) { activeBullet.classList.remove('swiper-pagination-bullet-active'); } } });
内容的提问来源于stack exchange,提问作者IIIu6ko
相关产品推荐
相关产品推荐

