嵌入YouTube视频继续播放封闭的容器

Embedded YouTube video keep playing on closed container

本文关键字:播放 YouTube 视频 继续 嵌入      更新时间:2023-09-26

我做了一个灯箱,一个通过点击jquery上的元素打开的窗口。
在图片上工作得很好,但如果我打开YouTube视频并播放它,关闭窗口后(显示:none),视频继续在后台播放。
我使用了本教程的灯箱。
YouTube视频作为iframe嵌入。

关闭窗口

<>之前$(".js- mode -close, . mode -overlay").click(function() {$("。modal-box .modal-overlay")。fadeOut(500, function() {$ (" .modal-overlay ") .remove ();});});之前

我怎样才能解决我的问题?

步骤1。启用iframe API的enablejsapi=1和添加一个id到iframe:

<iframe id="player" src="https://www.youtube.com/embed/MxMBueIjtv0?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

步骤2。加载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/

React解决方案


interface props {
  videoId: string;
}
function YoutubeEmbedded (props:Props) {
  const { videoId } = props;
  const pauseVideo = () => {
    // At the place of pauseVideo you can use "stopVideo", "playVideo"
    var iframe = document.querySelector("iframe");
    iframe?.contentWindow?.postMessage(
      '{"event":"command","func":"pauseVideo","args":""}',
      "*"
    );
  };
  const handleCloseBtnClick = () => {
    pauseVideo();
    setShowVideoModal(false);
  };
return(
  <iframe
    src={`https://www.youtube-nocookie.com/embed/${videoId}?enablejsapi=1`}
    title="YouTube video player"
    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
    allowFullScreen={true}
    frameBorder={0}
  />
  <button
    onClick={handleCloseBtnClick}
  />
)}