首页 > 解决方案 > 使用 javascript 即时更改视频并使用引导程序在浮动窗口上播放

问题描述

此代码使用引导程序在浮动窗口上播放视频。但我想使用 javascript 修改视频 src,这样我就可以拥有动态视频链接。我使用 onClick() 来更改视频的 src 但它不起作用。

function changevideo() {
  document.getElementById("source").src = "videos/projects/havoc/guide/guide_GOL_101_019_010.mp4";
}
<!DOCTYPE html>
<html lang="en">

<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js">
    </script>

</head>

<body>
    <button width="200" data-bs-toggle="modal" data-bs-target="#video" class="img" onClick="changevideo()">click me
        1</button>

    <!-- Modal -->
    <div class="modal fade" id="video">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body">
                    <video width="100%" autoplay loop>
                        <source id="source" src="">
                    </video>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

标签: javascripthtmlcssbootstrap-4

解决方案


你只是忘了按play

const video = document.getElementById("video-element");

const clear = (node) => {
    while (node.firstChild) {
        node.removeChild(node.lastChild);
    }
};


const changevideo = () => {
  const source = document.createElement('SOURCE');
  
  clear(video);
  
  source.type = "video/mp4";
  source.src = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
  
  video.appendChild(source);
  
  video.play();
}
<!DOCTYPE html>
<html lang="en">

<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js">
    </script>

</head>

<body>
    <button width="200" data-bs-toggle="modal" data-bs-target="#video" class="img" onClick="changevideo()">click me
        1</button>

    <!-- Modal -->
    <div class="modal fade" id="video">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body">
                    <video id="video-element" width="100%" loop>
                    </video>
                </div>
            </div>
        </div>
    </div>
</body>

</html>


推荐阅读