我在一个lightbox上工作,一个通过在jQuery上单击元素打开的窗口。
在图片上工作得很好,但是如果我打开一个YouTube视频并播放它,在关闭窗口(显示:无)之后,视频会在后台继续播放。
我在lightbox上使用了本教程。
YouTube视频是以iframe的形式嵌入的。
关闭窗口
$(".js-modal-close, .modal-overlay").click(function() { $(".modal-box, .modal-overlay").fadeOut(500, function() { $(".modal-overlay").remove(); }); });
我该怎么解决我的问题?
步骤1.使用enableJSAPI=1
启用iframe API,并将ID
添加到iframe:
<iframe id="player" src="https://www.youtube.com/embed/MxMBueIjtv0?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
第二步。加载API并使用步骤1中的id创建播放器。对于这个演示,我使用了player
(可能是一个糟糕的选择):
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
/* probably should tie into the `onReady` event,
but for this demo's purpose it's unnecessary.
the video will probably be ready by the time
you get to the close button. */
player = new YT.Player('player');
}
步骤3.在关闭模型段中调用StopVideo
函数:
$(".js-modal-close, .modal-overlay").click(function() {
player.stopVideo(); /* you can optionally also set the video back
at the beginning with `player.seekTo(0);` */
$(".modal-box, .modal-overlay").fadeOut(500, function() {
$(".modal-overlay").remove();
});
});
文档:https://developers.google.com/youtube/iframe_api_reference
演示:http://jsfiddle.net/4f5dksj5/