我有问题。我在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();
}
在这段代码中,我必须添加脚本和尽可能多的类视频。有没有其他方法可以让我在每次添加其他视频时都不必添加脚本?
我尝试使用document.getElementsByClassName("video")
,但它无效。如何在1页中添加尽可能多的视频,但我不必添加其他脚本?
答案 0 :(得分: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>
答案 1 :(得分:0)
我看到你已经有了解决方案,但这是我的想法:)
每个按钮都有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();
}
}