You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在关闭HTML5模态框时停止视频播放

解决Bootstrap模态框关闭后视频后台继续播放的问题

问题根源在于两个遗漏点:

  1. 你给关闭按钮绑定了pauseVid()函数,但没有实现这个函数的具体逻辑
  2. Bootstrap模态框的关闭方式不止点击关闭按钮(比如点击模态框外部、按ESC键),这些场景下你的暂停逻辑不会触发

修复方案

  1. 实现pauseVid()函数,不仅暂停视频,还要清空视频源以彻底终止播放、释放资源
  2. 监听Bootstrap模态框的hidden.bs.modal事件,确保无论以哪种方式关闭模态框,都能执行视频暂停逻辑

修改后的完整代码

脚本部分

<script>
function ShowData(value) {
    const video = document.getElementById("linkVideo");
    video.setAttribute('src', value);
    $('#modalVideo').modal('show');
}

function pauseVid() {
    const video = document.getElementById("linkVideo");
    video.pause();
    // 清空视频源,彻底终止播放并释放资源
    video.setAttribute('src', '');
}

// 监听模态框隐藏事件,覆盖所有关闭场景
$('#modalVideo').on('hidden.bs.modal', function () {
    pauseVid();
});
</script>

模态框代码(仅需保留原有结构,关闭按钮的onclick可保留)

<div class="modal fade" id="modalVideo" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-dialog-centered modal-dialog-scrollable modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalCenterTitle">Video</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="pauseVid()">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <center>
                    <video width="1280" height="720" controls autoplay id="linkVideo" >
                    </video>
                </center>
            </div>
            <div class="modal-footer">
            </div>
        </div>
    </div>
</div>

补充说明

  • hidden.bs.modal事件会在模态框完全隐藏后触发,覆盖所有关闭场景(点击按钮、点击背景、ESC键)
  • 清空视频的src属性可以避免视频在后台持续加载或播放,彻底释放浏览器资源

内容的提问来源于stack exchange,提问作者Patcharakorn Prom.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:04:57