如何用一个代码块控制多个视频

How to control many videos with a single code block

我有问题。我在 1 页中有 2 个视频。我的代码是这样的:

<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
    <div class="thumbnail">
        <div class="thumbnail-img">
            <div class="embed-responsive embed-responsive-16by9">
                <video id="video2">
                    <source src="video/inspiration-1.mp4" type="video/mp4">
                </video>
            </div>
            <button class="btn btn-primary play" onclick="playPause1()">
                <li class="fa fa-play"></li>
            </button>
        </div>
        <div class="caption">
            <h5 class="h5-big">HOW TO </h5>
            <a href=".detil.html" class="uppercase bold">recipe</a>
        </div>
    </div>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
    <div class="thumbnail">
        <div class="thumbnail-img">
            <div class="embed-responsive embed-responsive-16by9">
                <video id="video1">
                    <source src="video/inspiration-1.mp4" type="video/mp4">
                </video>
            </div>
            <button class="btn btn-primary play" onclick="playPause()">
                <li class="fa fa-play"></li>
            </button>
        </div>
        <div class="caption">
            <h5 class="h5-big">HOW TO </h5>
            <a href=".detil.html" class="uppercase bold">recipe</a>
        </div>
    </div>
</div>
var myVideo = document.getElementById("video1");

function playPause() {
    if (myVideo.paused)
        myVideo.play();
    else
        myVideo.pause();
}

var myVideoa = document.getElementById("video2");

function playPause1() {
    if (myVideoa.paused)
        myVideoa.play();
    else
        myVideoa.pause();
}

在此代码中,我必须添加脚本以及我拥有的视频中多达 class 的内容。有没有其他方法可以让我在想添加另一个视频时不必添加脚本?

我尝试使用 document.getElementsByClassName("video") 但它不起作用。如何在 1 个页面中添加尽可能多的视频,但我不必添加额外的脚本?

您可以将单个事件处理程序应用于所有 button 元素并遍历 DOM 以找到它们相关的 video 元素。当您用 jQuery 标记问题时,这里有一个 jQuery 实现:

$('.play').click(function() {
    var video = $(this).closest('.thumbnail').find('video')[0];
    if (video.paused)
        video.play();
    else
        video.pause();
});
<button class="btn btn-primary play">
    <li class="fa fa-play"></li>
</button>

我看到你已经有了解决方案,但这是我的想法:)

每个按钮都有视频的 ID

<button class="btn btn-primary play" id="video1" onclick="playPause()"><li class="fa fa-play"></li></button>

<button class="btn btn-primary play" id="video2" onclick="playPause()"><li class="fa fa-play"></li></button>

那么,您的脚本将如下所示:

 $("button").click(function(){
    var videoId = $(this).attr("id");
  playPause(videoId);

});


function playPause(videoId){
  var myVideo = document.getElementById(videoId); 

      if (myVideo.paused){
        myVideoa.play(); 
      }else {
        myVideo.pause(); 
      }
 }