Javascript 隐藏 iframe 时如何暂停 YouTube 播放器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8667882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:59:21  来源:igfitidea点击:

How to pause a YouTube player when hiding the iframe?

javascriptyoutube-apiyoutube-javascript-api

提问by 0161-Jon

I have a hidden div containing a YouTube video in an <iframe>. When the user clicks on a link, this div becomes visible, the user should then be able to play the video.

我有一个隐藏的 div,其中包含一个<iframe>. 当用户单击链接时,此 div 变得可见,然后用户应该能够播放视频。

When the user closes the panel, the video should stop playback. How can I achieve this?

当用户关闭面板时,视频应停止播放。我怎样才能做到这一点?

Code:

代码:

<!-- link to open popupVid -->
<p><a href="javascript:;" onClick="document.getElementById('popupVid').style.display='';">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>

<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">

  <iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40" frameborder="0" allowfullscreen></iframe>

  <br /><br /> 
  <a href="javascript:;" onClick="document.getElementById('popupVid').style.display='none';">
  close
  </a>
</div><!--end of popupVid -->

回答by Rob W

The easiest way to implement this behaviour is by calling the pauseVideoand playVideomethods, when necessary. Inspired by the result of my previous answer, I have written a pluginless function to achieve the desired behaviour.

实现此行为的最简单方法是在必要时调用pauseVideoplayVideo方法。受到我之前回答结果的启发,我编写了一个无插件函数来实现所需的行为。

The only adjustments:

唯一的调整:

  • I have added a function, toggleVideo
  • I have added ?enablejsapi=1to YouTube's URL, to enable the feature
  • 我添加了一个功能, toggleVideo
  • 我已添加?enablejsapi=1到 YouTube 的 URL,以启用该功能

Demo: http://jsfiddle.net/ZcMkt/
Code:

演示:http: //jsfiddle.net/ZcMkt/
代码:

<script>
function toggleVideo(state) {
    // if state == 'hide', hide. Else: show video
    var div = document.getElementById("popupVid");
    var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
    div.style.display = state == 'hide' ? 'none' : '';
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}
</script>

<p><a href="javascript:;" onClick="toggleVideo();">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>

<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
   <iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
   <br /><br />
   <a href="javascript:;" onClick="toggleVideo('hide');">close</a>

回答by DrewT

Here's a jQuery take on RobW's answer for use hiding /pausing an iframe in a modal window:

这是 jQuery 对 RobW 使用在模式窗口中隐藏/暂停 iframe 的回答:

    function toggleVideo(state) {
        if(state == 'hide'){
            $('#video-div').modal('hide');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
        }
        else {
            $('#video-div').modal('show');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
        }
    }

The html elements referred to are the modal div itself (#video-div) calling the show / hide methods, and the iframe (#video-iframe) which has the video url as is src="" and has the suffix enablejsapi=1?which enables programmatic control of the player (ex. .

引用的 html 元素是调用 show / hide 方法的模态 div 本身(#video-div),以及具有视频 url 的 iframe (#video-iframe) 为 src="" 并具有后缀enablejsapi=1 ? 这可以实现对播放器的编程控制(例如. .

For more on the html see RobW's answer.

有关 html 的更多信息,请参阅 RobW 的回答。

回答by quartarian

Here is a simple jQuery snippet to pause all videos on the page based off of RobW's and DrewT's answers:

这是一个简单的 jQuery 片段,用于根据 RobW 和 DrewT 的回答暂停页面上的所有视频:

jQuery("iframe").each(function() {
  jQuery(this)[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')
});

回答by Paula

Hey an easy way is to simply set the src of the video to nothing, so that the video will desapear while it's hidden an then set the src back to the video you want when you click on the link that opens the video.. to do that simply set an id to the youtube iframe and call the src function using that id like this:

嘿,一个简单的方法是简单地将视频的 src 设置为空,以便视频在隐藏时消失,然后在单击打开视频的链接时将 src 设置回您想要的视频。只需将 id 设置为 youtube iframe 并使用该 id 调用 src 函数,如下所示:

<script type="text/javascript">
function deleteVideo()
{
document.getElementById('VideoPlayer').src='';
}

function LoadVideo()
{
document.getElementById('VideoPlayer').src='http://www.youtube.com/embed/WHAT,EVER,YOUTUBE,VIDEO,YOU,WHANT';
}
</script>

<body>

<p onclick="LoadVideo()">LOAD VIDEO</P>
<p onclick="deleteVideo()">CLOSE</P>

<iframe id="VideoPlayer" width="853" height="480" src="http://www.youtube.com/WHAT,EVER,YOUTUBE,VIDEO,YOU,HAVE" frameborder="0" allowfullscreen></iframe>

</boby>

回答by Nick F

Since you need to set ?enablejsapi=truein the src of the iframe before you can use the playVideo/ pauseVideocommands mentioned in other answers, it might be useful to add this programmatically via Javascript (especially if, eg. you want this behaviour to apply to videos embedded by other users who have just cut and paste a YouTube embed code). In that case, something like this might be useful:

由于您需要?enablejsapi=true在 iframe 的 src 中进行设置,然后才能使用其他答案中提到的playVideo/pauseVideo命令,因此通过 Javascript 以编程方式添加它可能会很有用(尤其是如果,例如,您希望此行为应用于其他人嵌入的视频)刚刚剪切和粘贴 YouTube 嵌入代码的用户)。在这种情况下,这样的事情可能会有用:

function initVideos() {

  // Find all video iframes on the page:
  var iframes = $(".video").find("iframe");

  // For each of them:
  for (var i = 0; i < iframes.length; i++) {
    // If "enablejsapi" is not set on the iframe's src, set it:
    if (iframes[i].src.indexOf("enablejsapi") === -1) {
      // ...check whether there is already a query string or not:
      // (ie. whether to prefix "enablejsapi" with a "?" or an "&")
      var prefix = (iframes[i].src.indexOf("?") === -1) ? "?" : "&amp;";
      iframes[i].src += prefix + "enablejsapi=true";
    }
  }
}

...if you call this on document.readythen all iframes in a div with a class of "video" will have enablejsapi=trueadded to their source, which allows the playVideo / pauseVideo commands to work on them.

...如果您调用它,document.ready则 div 中具有“视频”类的所有 iframe 都将enablejsapi=true添加到它们的源中,这允许 playVideo / pauseVideo 命令对它们起作用。

(nb. this example uses jQuery for that one line that sets var iframes, but the general approach should work just as well with pure Javascript if you're not using jQuery).

(注意,这个例子在设置 的那一行使用 jQuery var iframes,但如果你不使用 jQuery,一般方法应该与纯 Javascript 一样好用)。

回答by david

You can stop the video by calling the stopVideo()method on the YouTube player instance before hiding the div e.g.

您可以通过stopVideo()在隐藏 div 之前调用YouTube 播放器实例上的方法来停止视频,例如

player.stopVideo()

For more details see here: http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls

有关详细信息,请参见此处:http: //code.google.com/apis/youtube/js_api_reference.html#Playback_controls

回答by skribbz14

RobW's way worked great for me. For people using jQuery here's a simplified version that I ended up using:

RobW 的方式对我很有用。对于使用 jQuery 的人,这是我最终使用的简化版本:

var iframe = $(video_player_div).find('iframe');

var src = $(iframe).attr('src');      

$(iframe).attr('src', '').attr('src', src);

In this example "video_player" is a parent div containing the iframe.

在这个例子中,“video_player”是一个包含 iframe 的父 div。

回答by Poldon

I wanted to share a solution I came up with using jQuery that works if you have multiple YouTube videos embedded on a single page. In my case, I have defined a modal popup for each video as follows:

我想分享一个我想出的使用 jQuery 的解决方案,如果您在单个页面上嵌入了多个 YouTube 视频,该解决方案就有效。就我而言,我为每个视频定义了一个模态弹出窗口,如下所示:

<div id="videoModalXX">
...
    <button onclick="stopVideo(videoID);" type="button" class="close"></button>
    ...
    <iframe width="90%" height="400" src="//www.youtube-nocookie.com/embed/video_id?rel=0&enablejsapi=1&version=3" frameborder="0" allowfullscreen></iframe>
...
</div>

In this case, videoModalXX represents a unique id for the video. Then, the following function stops the video:

在这种情况下,videoModalXX 代表视频的唯一 ID。然后,以下函数停止视频:

function stopVideo(id)
{
    $("#videoModal" + id + " iframe")[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}

I like this approach because it keeps the video paused where you left off in case you want to go back and continue watching later. It works well for me because it's looking for the iframe inside of the video modal with a specific id. No special YouTube element ID is required. Hopefully, someone will find this useful as well.

我喜欢这种方法,因为它可以让视频在您离开的地方暂停,以防您想回去继续观看。它对我来说效果很好,因为它正在寻找具有特定 id 的视频模式内的 iframe。不需要特殊的 YouTube 元素 ID。希望有人会发现这也很有用。

回答by rakesh kejriwal

just remove src of iframe

只需删除 iframe 的 src

$('button.close').click(function(){
    $('iframe').attr('src','');;
});

回答by hong4rc

This approach requires jQuery. First, select your iframe:

这种方法需要jQuery。首先,选择您的 iframe:

var yourIframe = $('iframe#yourId');
//yourId or something to select your iframe.

Now you select button play/pause of this iframe and click it

现在您选择此 iframe 的按钮播放/暂停并单击它

$('button.ytp-play-button.ytp-button', yourIframe).click();

I hope it will help you.

我希望它会帮助你。