JavaScript:嵌入式YouTube视频无法在模态弹出窗口中播放



我有以下代码,它查看.vma_iFramePopup特定的 css 类,并从中获取存储在src中的链接。然后将其加载到模式弹出窗口中。

$(document).ready(function () {
$(".vma_overlay").click(function (event) {
var $videoSrcOriginal = $(event.target).siblings('.vma_iFramePopup').attr("src");
// Check if the embedded youtube url has any attributes appended
// by looking for a '?' in the url.
// If one is found, append our autoplay attribute using '&',
// else append it with '?'.
if ($videoSrcOriginal.indexOf('?') > -1) {
var $videoSrc = $videoSrcOriginal
// when the modal is opened autoplay it
$('#vma_ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay
var $videoSrcAuto = $videoSrc + "&autoplay=1&mute=1";
$("#vma_video").attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
})
} else {
var $videoSrc = $(".vma_iFramePopup").attr("src");
// when the modal is opened autoplay it
$('#vma_ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay
var $videoSrcAuto = $videoSrc + "?autoplay=1&mute=1";
$("#vma_video").attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
})
}
// stop playing the youtube video when modal is closed
$('#vma_ModalBox').on('hide.bs.modal', function (e) {
$("#vma_video").attr('src', $videoSrc);
$('body').removeClass("modalyt");
})
});
});

我被告知视频没有在模态中播放。加载时的模式为空。

当我检查浏览器控制台时,我没有看到任何相关错误。

当我在模态弹出窗口中检查 iframe 时,我看到它说

来源(未知)

在 SRC 元素中:

<iframe class="embed-responsive-item" width="80%" height="80%" src(unknown) id="vma_video" allowfullscreen="" data-gtm-yt-inspected-9256558_25="true">></iframe>

我无法确定为什么会发生这种情况?

我尝试在实时网站上摆弄您的代码的非常轻微的变化,它似乎有效:

$('.vma_overlay').on('click', function() {
var $videoSrcOriginal = $(this).siblings('.vma_iFramePopup').attr("src");
if ($videoSrcOriginal.indexOf('?') > -1) {
$('#vma_ModalBox').show();
var $videoSrcAuto = $videoSrcOriginal + "&autoplay=1&mute=1";
$('#vma_ModalBox #vma_video').attr('src', $videoSrcAuto);
$('body').addClass("modalyt");
}
});

事实证明,在这种特殊情况下,解决方案是替换:

$(document).ready(function () {

跟:

window.onload = function () {

由于特定于我们的设置的某种原因,jquery 准备文档的方式没有触发。

最新更新