jQuery防止用户关闭视频后自动播放



我正在编写一个脚本,将弹出一个视频并自动播放它下面的例子。一切都很好,但是当用户关闭视频时,它继续在后台播放。在用户关闭视频后,如何让浏览器关闭自动播放?

$(document).ready(function() {
$('#headerVideoLink').magnificPopup({
type: 'inline'
});
});
#headerPopup {
width: 75%;
margin: 0 auto;
position: relative;
top: 80px;
}
#headerPopup iframe {
width: 100%;
margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="headerPopup" class="mfp-hide">
<iframe width="854" height="480" src="https://www.youtube.com/embed/qN3OueBm9F4?autoplay=1" frameborder="0" allow="autoplay" allowfullscreen></iframe>
</div>

在我看来,你的问题没有直接的答案。这是人们在网站上播放视频时经常遇到的问题。

最好的方法是使用Bootstrap CSS框架,因为它有模态(弹出窗口),你可以在其中添加视频,每当你关闭或打开它们时,它都会暴露可以触发功能的事件。

在这种情况下,您需要jQuery在打开和关闭模态时做一些事情。为了避免视频在用户关闭模态时在背景上播放,一种方法是删除iframe的src属性的内容,这将阻止iframe继续播放视频。然后当用户打开模态添加链接回来。如果你不这样做,将会发生的是,用户可能点击一次视频,它会正常工作,但是当jQuery删除视频的链接后,它就不能工作了。

jQuery脚本我使用这个目的:

$(document).ready(function(){

// Save the url of the video in a variable
var url = $("#MyVideo").attr('src');

// When the modal is closed remove the url of the iframe
$("#myModal").on('hide.bs.modal', function(){
$("#MyVideo").attr('src', '');
});

// When the modal is opened, add the url to the iframe
$("#myModal").on('show.bs.modal', function(){
$("#MyVideo").attr('src', url);
});
});

你可以在这里阅读更多关于Bootstrap情态的工作原理。这些事件的细节和解释在这一页的底部。

最新更新