首页 > 解决方案 > 如何在单个html页面中拥有多个视频播放器

问题描述

我在使用 YouTube api 时遇到问题:我正在开发一个网站,并且我希望在打开他的相关图像时开始播放视频:我将这段代码用于其中的第一个并且它可以工作:

              <script>
                // 2. This code loads the IFrame Player API code asynchronously.
               // var tag = document.createElement('script');

               // tag.src = "https://www.youtube.com/iframe_api";
                //var firstScriptTag = document.getElementsByTagName('script')[0];
                firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


                 function onYouTubeIframeAPIReady() {
                  player = new YT.Player('player', {
                    height: '360',
                    width: '640',
                    videoId: 'M7lc1UVf-VE',
                    events: {
                      'onReady': onPlayerReady,
                      'onStateChange': onPlayerStateChange
                    }
                  });
                }
              </script>
              <button class="btn btn-primary" data-dismiss="modal" type="button">
                <i class="fa fa-times"></i>
                Chiudi</button>
            </div>

现在,如果我将相同的代码放在另一张照片和同一页面上的另一个视频中,它不起作用并给我这个错误:“TypeError:无法读取未定义的属性'parentNode'”。(如果我点击其他照片,即使我更改参考,它也不会显示视频)(我对 boostrap 和 js 很陌生)如果你能给我一些提示,我将不胜感激,谢谢,祝你有美好的一天(对不起为了我蹩脚的英语)

标签: javascripthtmlyoutube-apiyoutube-javascript-apivideo-player

解决方案


请尝试此代码,因为我不明白您的报价,您可以使用此代码。我认为这段代码很有用。

正如您提到的问题中只有两个具有相同来源的视频标签,这是一种可能性。思路如下:

<--script-->

    var myvid = document.getElementById('myvideo');

    myvid.addEventListener('ended', function(e) {
      // get the active source and the next video source.
      // I set it so if there's no next, it loops to the first one
      var activesource = document.querySelector("#myvideo source.active");
      var nextsource = document.querySelector("#myvideo source.active + source") || document.querySelector("#myvideo source:first-child");

      // deactivate current source, and activate next one
      activesource.className = "";
      nextsource.className = "active";

      // update the video source and play
      myvid.src = nextsource.src;
      myvid.play();
    });


<!--html-->
    <video id="myvideo" width="320" height="240" controls style="background:black">
      <source class="active" src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" />
      <source src="http://www.w3schools.com/html/movie.mp4" type="video/mp4" />
    </video>

推荐阅读