我在同一页面上有3个HTML5视频,我想暂停/静音除我选择的视频之外的所有视频。当我在点击时使用事件侦听器定位父div时,效果似乎很好,但是在定位视频控件时,也需要它同时工作。
但是,当我开始在html5媒体事件(例如“暂停”或“播放”)上测试事件监听器时。我无法收听将“ video.play()”应用于事件而不会中断。
var M = M || {};
var $allVideos = $('video');
M.playVideo = function($target) {
var $video = $target.children('video');
var $previewImage = $target.children('img.previewImage');
$allVideos.map(function(index, element, something){
element.pause();
element.muted = true;
});
if($video[0].paused){
$previewImage.css('display', 'none');
$video[0].muted = false;
$video[0].play();
} else {
$video[0].pause();
}
}
$('.parallax-box').on('click', function (e) {
e.preventDefault();
M.playVideo($(this));
});
$('video').on('play', function(e) {
//pause all videos initially
$allVideos.map(function(index, element, something){
element.pause();
});
//if the target video is paused, play it
if($(this)[0].paused){
$(this)[0].play(); // play() just keeps running breaking the browser
}
}
<a id="video1" class="video-box" target="_blank" href="#" title="video">
<video id="vid1" preload="metadata" loop controls>
<source src="vid1.mp4"/>
</video>
<img class="previewImage" src="image1.jpg" />
</a>
<a id="video2" class="video-box" target="_blank" href="#" title="video">
<video id="vid2" preload="metadata" loop controls>
<source src="vid2.mp4"/>
</video>
<img class="previewImage" src="image2.jpg" />
</a>
<a id="video3" class="video-box" target="_blank" href="#" title="video">
<video id="vid3" preload="metadata" loop controls>
<source src="vid3.mp4"/>
</video>
<img class="previewImage" src="image3.jpg" />
</a>
答案 0 :(得分:4)
您可以使用not()
var $allVideos = $('video');
$('video').on('play', function(e) {
$allVideos.not(this).each(function() {
this.pause()
})
});
video {width: 300px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<video id="vid1" preload="metadata" loop controls>
<source src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.160p.webm" />
</video>
<video id="vid2" preload="metadata" loop controls>
<source src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.160p.webm" />
</video>
<video id="vid3" preload="metadata" loop controls>
<source src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.160p.webm" />
</video>