Swiper.js幻灯片视频:非可视状态下自动暂停方案咨询
解决Swiper幻灯片视频切换后后台播放的问题
问题描述
使用Swiper库开发幻灯片时,在幻灯片中嵌入HTML视频后出现以下问题:播放某幻灯片内的视频并切换至其他幻灯片时,视频仍会在后台持续播放,影响用户体验。需要实现视频不在视图中时自动暂停。
基础代码示例
Swiper初始化代码:
// SWIPER SERVICES START if (document.body.id === "services") { const swiper = new Swiper(".swiper", { loop: true, speed: 600, autoplay: { delay: 15000, }, direction: "horizontal", pagination: { el: ".swiper-pagination", }, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, scrollbar: { el: ".swiper-scrollbar", }, }); } // SWIPER SERVICES END
幻灯片结构:
<div class="swiper-slide"> <p class="note date">2023</p> <p class="note"> <a href="https://video.dk/" target="_blank" rel="noopener noreferrer" ><span>Showreel</span ><span > <i class="fa-solid fa-arrow-up-right-from-square"></i ></span> </a> </p> <video src="/img/showreel.mp4" preload="metadata" controls="controls" playsinline role="video" aria-label="label" aria-describedby="<?php echo $lang['asset_40'] ?>" poster="/img/cover" ></video> </div>
解决方案
核心是利用Swiper的slideChange事件(幻灯片切换完成时触发),在事件回调中处理视频的暂停逻辑。
方法1:全局暂停所有视频(简单高效)
修改Swiper初始化代码,添加on配置项监听slideChange事件,遍历所有幻灯片内的视频并暂停:
// SWIPER SERVICES START if (document.body.id === "services") { const swiper = new Swiper(".swiper", { loop: true, speed: 600, autoplay: { delay: 15000, }, direction: "horizontal", pagination: { el: ".swiper-pagination", }, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, scrollbar: { el: ".swiper-scrollbar", }, // 新增事件监听 on: { slideChange: function () { // 获取所有幻灯片中的video元素 const allVideos = document.querySelectorAll(".swiper-slide video"); // 遍历暂停所有视频 allVideos.forEach(video => video.pause()); } } }); } // SWIPER SERVICES END
方法2:精准暂停非活跃幻灯片的视频
如果需要仅暂停当前未显示的幻灯片内的视频,可通过Swiper的活跃幻灯片类名swiper-slide-active筛选:
on: { slideChange: function () { // 获取所有非活跃幻灯片中的视频 const inactiveVideos = document.querySelectorAll(".swiper-slide:not(.swiper-slide-active) video"); inactiveVideos.forEach(video => video.pause()); } }
额外优化:处理自动播放冲突
若开启了Swiper的autoplay,可在用户播放视频时暂停自动播放,视频暂停后恢复自动播放,提升体验:
// SWIPER SERVICES START if (document.body.id === "services") { const swiper = new Swiper(".swiper", { // 原有配置... on: { slideChange: function () { const allVideos = document.querySelectorAll(".swiper-slide video"); allVideos.forEach(video => video.pause()); } } }); // 给所有视频添加播放/暂停监听 document.querySelectorAll(".swiper-slide video").forEach(video => { video.addEventListener("play", () => swiper.autoplay.stop()); video.addEventListener("pause", () => swiper.autoplay.start()); }); } // SWIPER SERVICES END
注意事项
- 该方案兼容Swiper的
loop模式,复制的幻灯片也会被正确识别。 pause()方法调用时,若视频已处于暂停状态不会报错,无需额外判断。- 确保视频选择器能覆盖所有幻灯片内的视频,示例中
.swiper-slide video可满足需求。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

