当人们点击视频时,我的编辑希望我们的嵌入式YouTube视频以模式叠加的形式开始播放。
我设法将视频加载到模式叠加中并开始播放。但是,只有将&mute=1
附加到YouTube嵌入网址后,我才能让它们播放。
有没有办法让他们播放音频?毕竟,只有在用户表示有意通过点击观看视频后,我们才将视频加载到模态中。
我的HTML:
<section>
<div class="container">
<div class="row">
<div class="sizer">
<div class="overlay" data-toggle="modal" data-target="#ModalBox">
<iframe
src="https://www.youtube.com/embed/iRYDYrj3Bfw"
frameborder="0"
allow="autoplay; encrypted-media"
allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</section>
<!-- Modal -->
<div class="modal fade" id="ModalBox" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="" id="video" allowfullscreen>></iframe>
</div>
</div>
</div>
</div>
</div>
我的CSS:
.width {
width: 560px;
height: 315px;
}
.sizer {
width: 560px;
height: 315px;
}
.overlay {
position: relative !important;
cursor: pointer !important;
width: inherit !important;
}
.overlay:before {
content: '';
position: absolute;
height: 100%;
width: 100%;
transition: all 200ms ease-in;
opacity: 0;
}
.overlay:hover:before {
background: #999999;
opacity: 0.3;
}
body {
margin: 2rem;
}
.modal-dialog {
max-width: 90%;
margin: 30px auto;
}
.modal-body {
position: relative;
padding: 0px;
}
.close {
position: absolute;
right: -30px;
top: 0;
z-index: 999;
font-size: 2rem;
font-weight: normal;
color: #fff;
opacity: 1;
}
.modal-backdrop {
opacity: 0.8 !important;
background: #000;
}
我的JavaScript:
$(document).ready(function() {
// get the video src from the youtube iframe
var $videoSrc = $("iframe").attr("src").split('?')[0];
// when the modal is opened autoplay it
$('#ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay and not to show related videos.
var $videoSrcAuto = $videoSrc + "?rel=0&autoplay=1&mute=1";
$("#video").attr('src',$videoSrcAuto);
})
// stop playing the youtube video when modal is closed
$('#ModalBox').on('hide.bs.modal', function (e) {
$("#video").attr('src',$videoSrc);
})
// document ready
});
一个有效的示例:https://codepen.io/CodeChaos/pen/NExWWo
更新1:
经进一步研究,此问题似乎仅在Chrome中发生。在Edge和Firefox中,即使不静音也可以自动播放视频。