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

将Bootstrap4视频模态框迁移至无jQuery的Bootstrap5的实现问题

Bootstrap 4 内嵌视频模态框迁移 Bootstrap 5(无jQuery)适配方案

一、HTML 代码调整

需要修改2处兼容Bootstrap 5的属性规范,调整后完整代码如下:

<button type="button" class="video-btn" data-bs-toggle="modal" data-bs-target="#videoModal" data-bs-src="https://www.youtube.com/embed/EzDC8aAJln0" >
  <img src="/img/video/dbschema-video.svg" class="img-fluid" alt="DbSchema Video Presentation">
</button>

<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="dbschemaModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body">
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        <div class="ratio ratio-16x9">
          <iframe class="embed-responsive-item" src="" id="video" allowscriptaccess="always" allow="autoplay"></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

调整点说明:

  • 关闭按钮原data-dismiss="modal"替换为Bootstrap 5标准的data-bs-dismiss="modal"
  • 关闭按钮原class="close"替换为Bootstrap 5内置的btn-close类,可直接复用默认关闭样式,无需额外自定义CSS

二、原生JavaScript代码(完全替代原有jQuery版本)

改造后代码无任何jQuery依赖,功能和原有逻辑完全一致:

document.addEventListener('DOMContentLoaded', function() {
  let videoSrc;
  // 绑定所有视频触发按钮的点击事件,读取视频地址
  document.querySelectorAll('.video-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      videoSrc = this.dataset.bsSrc;
    })
  })

  const videoModal = document.getElementById('videoModal');
  const videoFrame = document.getElementById('video');

  // 模态框完全展开后自动加载播放视频
  videoModal.addEventListener('shown.bs.modal', function() {
    videoFrame.setAttribute('src', videoSrc + "?autoplay=1&modestbranding=1&showinfo=0");
  })

  // 模态框关闭后重置视频地址,停止播放
  videoModal.addEventListener('hide.bs.modal', function() {
    videoFrame.setAttribute('src', videoSrc);
  })
})

改造逻辑说明:

  • 用原生DOMContentLoaded事件替代jQuery的$(document).ready
  • 用原生选择器querySelectorAll/getElementById替代jQuery选择器
  • 用addEventListener替代jQuery的on方法绑定事件
  • 用元素内置的dataset属性读取自定义data值,setAttribute方法修改iframe的src属性

内容的提问来源于stack exchange,提问作者DbSchema

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:54:05