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

时间:2020-12-31 18:57:28

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,它在

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 -->

14 个解决方案

#1


172  

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

实现这种行为的最简单方法是在必要时调用包塞维迪奥和playVideo方法。受我之前回答的启发,我编写了一个无插件函数来实现所需的行为。

The only adjustments:

唯一的调整:

  • I have added a function, toggleVideo
  • 我添加了一个函数,toggleVideo
  • I have added ?enablejsapi=1 to YouTube's URL, to enable the feature
  • 我已经将?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>

#2


23  

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元素是modal div本身(#video div),它调用show / hide方法,iframe (#video-iframe),它的视频url是src="",并有后缀enablejsapi=1?实现对播放器的程序化控制(例如。

For more on the html see RobW's answer.

更多关于html的内容见RobW的答案。

#3


15  

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":""}', '*')
});

#4


9  

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>

#5


6  

Since you need to set ?enablejsapi=true in the src of the iframe before you can use the playVideo / pauseVideo commands 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:

由于在使用其他答案中提到的playVideo / pauseVideo命令之前,您需要在iframe的src中设置?enablejsapi=true,因此通过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.ready then all iframes in a div with a class of "video" will have enablejsapi=true added to their source, which allows the playVideo / pauseVideo commands to work on them.

…如果你调用文档。准备好了,所有的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).

(nb。这个示例对设置var iframe的一行使用jQuery,但是如果不使用jQuery,那么一般的方法应该与纯Javascript一样有效)。

#6


5  

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

在隐藏div例之前,可以通过调用YouTube player实例上的stopVideo()方法来停止该视频。

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

#7


4  

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

罗伯的方式对我来说很有用。对于使用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。

#8


4  

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。希望有人也会发现这很有用。

#9


2  

just remove src of iframe

只需移除iframe的src

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

#10


1  

Rob W answer helped me figure out how to pause a video over iframe when a slider is hidden. Yet, I needed some modifications before I could get it to work. Here is snippet of my html:

Rob W的回答帮助我找到了当一个滑动条被隐藏时如何在iframe上暂停视频的方法。然而,我需要一些修改才能使它生效。下面是我的html代码片段:

<div class="flexslider" style="height: 330px;">
  <ul class="slides">
    <li class="post-64"><img src="http://localhost/.../Banner_image.jpg"></li>
    <li class="post-65><img  src="http://localhost/..../banner_image_2.jpg "></li>
    <li class="post-67 ">
        <div class="fluid-width-video-wrapper ">
            <iframe frameborder="0 " allowfullscreen=" " src="//www.youtube.com/embed/video-ID?enablejsapi=1 " id="fitvid831673 "></iframe>
        </div>
    </li>
  </ul>
</div>

Observe that this works on localhosts and also as Rob W mentioned "enablejsapi=1" was added to the end of the video URL.

注意,在本地主机上工作,同时Rob W提到的“enablejsapi=1”被添加到视频URL的末尾。

Following is my JS file:

以下是我的JS文件:

jQuery(document).ready(function($){
    jQuery(".flexslider").click(function (e) {
        setTimeout(checkiframe, 1000); //Checking the DOM if iframe is hidden. Timer is used to wait for 1 second before checking the DOM if its updated

    });
});

function checkiframe(){
    var iframe_flag =jQuery("iframe").is(":visible"); //Flagging if iFrame is Visible
    console.log(iframe_flag);
    var tooglePlay=0;
    if (iframe_flag) {                                //If Visible then AutoPlaying the Video
        tooglePlay=1;
        setTimeout(toogleVideo, 1000);                //Also using timeout here
    }
    if (!iframe_flag) {     
        tooglePlay =0;
        setTimeout(toogleVideo('hide'), 1000);  
    }   
}

function toogleVideo(state) {
    var div = document.getElementsByTagName("iframe")[0].contentWindow;
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    div.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}; 

Also, as a simpler example, check this out on JSFiddle

另外,作为一个更简单的示例,请在JSFiddle检查这个函数

#11


0  

RobW's answers here and elsewhere were very helpful, but I found my needs to be much simpler. I've answered this elsewhere, but perhaps it will be useful here also.

罗柏在这里和其他地方的回答非常有帮助,但我发现我的需要要简单得多。我在别处已经回答过这个问题,但也许它在这里也会有用。

I have a method where I form an HTML string to be loaded in a UIWebView:

我有一种方法,我在UIWebView中生成一个HTML字符串:

NSString *urlString = [NSString stringWithFormat:@"https://www.youtube.com/embed/%@",videoID];

preparedHTML = [NSString stringWithFormat:@"<html><body style='background:none; text-align:center;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>var player; function onYouTubeIframeAPIReady(){player=new YT.Player('player')}</script><iframe id='player' class='youtube-player' type='text/html' width='%f' height='%f' src='%@?rel=0&showinfo=0&enablejsapi=1' style='text-align:center; border: 6px solid; border-radius:5px; background-color:transparent;' rel=nofollow allowfullscreen></iframe></body></html>", 628.0f, 352.0f, urlString];

You can ignore the styling stuff in the preparedHTML string. The important aspects are:

可以忽略preparedHTML字符串中的样式。重要的方面是:

  • Using the API to create the "YT.player" object. At one point, I only had the video in the iFrame tag and that prevented me from referencing the "player" object later with JS.
  • 使用API创建“YT”。球员”对象。在某一时刻,我只有iFrame标记中的视频,这使我无法在以后使用JS引用“player”对象。
  • I've seen a few examples on the web where the first script tag (the one with the iframe_api src tag) is omitted, but I definitely needed that to get this working.
  • 我在web上看到过一些示例,其中省略了第一个脚本标记(带有iframe_api src标记的那个),但我确实需要它来实现这个功能。
  • Creating the "player" variable at the beginning of the API script. I have also seen some examples that have omitted that line.
  • 在API脚本的开头创建“player”变量。我也看到一些例子省略了这一行。
  • Adding an id tag to the iFrame to be referenced in the API script. I almost forgot that part.
  • 向API脚本中要引用的iFrame添加id标记。我差点忘了那部分。
  • Adding "enablejsapi=1" to the end of the iFrame src tag. That hung me up for a while, as I initially had it as an attribute of the iFrame tag, which does not work/did not work for me.
  • 在iFrame src标记的末尾添加“enablejsapi=1”。这让我犹豫了一段时间,因为我最初把它作为iFrame标记的属性,它对我不起作用/不起作用。

When I need to pause the video, I just run this:

当我需要暂停视频时,我就运行这个:

[webView stringByEvaluatingJavaScriptFromString:@"player.pauseVideo();"];

Hope that helps!

希望会有帮助!

#12


0  

This is working fine to me with YT player

这对我来说很好

 createPlayer(): void {
  return new window['YT'].Player(this.youtube.playerId, {
  height: this.youtube.playerHeight,
  width: this.youtube.playerWidth,
  playerVars: {
    rel: 0,
    showinfo: 0
  }
});
}

this.youtube.player.pauseVideo();

this.youtube.player.pauseVideo();

#13


0  

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.

我希望它能对你有所帮助。

#14


0  

A more concise, elegant, and secure answer: add “?enablejsapi=1” to the end of the video URL, then construct and stringify an ordinary object representing the pause command:

一个更简洁,更优雅,更安全的答案:add ?将enablejsapi=1“到视频URL的末尾,然后构造和stringify一个表示暂停命令的普通对象:

const YouTube_pause_video_command_JSON = JSON.stringify(Object.create(null, {
    "event": {
        "value": "command",
        "enumerable": true
    },
    "func": {
        "value": "pauseVideo",
        "enumerable": true
    }
}));

Use the Window.postMessage method to send the resulting JSON string to the embedded video document:

使用窗口。postMessage方法将产生的JSON字符串发送到嵌入式视频文档:

// |iframe_element| is defined elsewhere.
const video_URL = iframe_element.getAttributeNS(null, "src");
iframe_element.contentWindow.postMessage(YouTube_pause_video_command_JSON, video_URL);

Make sure you specify the video URL for the Window.postMessage method’s targetOrigin argument to ensure that your messages won’t be sent to any unintended recipient.

确保为窗口指定视频URL。postMessage方法的targetOrigin参数,以确保您的消息不会被发送到任何无意的收件人。

#1


172  

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

实现这种行为的最简单方法是在必要时调用包塞维迪奥和playVideo方法。受我之前回答的启发,我编写了一个无插件函数来实现所需的行为。

The only adjustments:

唯一的调整:

  • I have added a function, toggleVideo
  • 我添加了一个函数,toggleVideo
  • I have added ?enablejsapi=1 to YouTube's URL, to enable the feature
  • 我已经将?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>

#2


23  

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元素是modal div本身(#video div),它调用show / hide方法,iframe (#video-iframe),它的视频url是src="",并有后缀enablejsapi=1?实现对播放器的程序化控制(例如。

For more on the html see RobW's answer.

更多关于html的内容见RobW的答案。

#3


15  

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":""}', '*')
});

#4


9  

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>

#5


6  

Since you need to set ?enablejsapi=true in the src of the iframe before you can use the playVideo / pauseVideo commands 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:

由于在使用其他答案中提到的playVideo / pauseVideo命令之前,您需要在iframe的src中设置?enablejsapi=true,因此通过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.ready then all iframes in a div with a class of "video" will have enablejsapi=true added to their source, which allows the playVideo / pauseVideo commands to work on them.

…如果你调用文档。准备好了,所有的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).

(nb。这个示例对设置var iframe的一行使用jQuery,但是如果不使用jQuery,那么一般的方法应该与纯Javascript一样有效)。

#6


5  

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

在隐藏div例之前,可以通过调用YouTube player实例上的stopVideo()方法来停止该视频。

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

#7


4  

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

罗伯的方式对我来说很有用。对于使用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。

#8


4  

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。希望有人也会发现这很有用。

#9


2  

just remove src of iframe

只需移除iframe的src

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

#10


1  

Rob W answer helped me figure out how to pause a video over iframe when a slider is hidden. Yet, I needed some modifications before I could get it to work. Here is snippet of my html:

Rob W的回答帮助我找到了当一个滑动条被隐藏时如何在iframe上暂停视频的方法。然而,我需要一些修改才能使它生效。下面是我的html代码片段:

<div class="flexslider" style="height: 330px;">
  <ul class="slides">
    <li class="post-64"><img src="http://localhost/.../Banner_image.jpg"></li>
    <li class="post-65><img  src="http://localhost/..../banner_image_2.jpg "></li>
    <li class="post-67 ">
        <div class="fluid-width-video-wrapper ">
            <iframe frameborder="0 " allowfullscreen=" " src="//www.youtube.com/embed/video-ID?enablejsapi=1 " id="fitvid831673 "></iframe>
        </div>
    </li>
  </ul>
</div>

Observe that this works on localhosts and also as Rob W mentioned "enablejsapi=1" was added to the end of the video URL.

注意,在本地主机上工作,同时Rob W提到的“enablejsapi=1”被添加到视频URL的末尾。

Following is my JS file:

以下是我的JS文件:

jQuery(document).ready(function($){
    jQuery(".flexslider").click(function (e) {
        setTimeout(checkiframe, 1000); //Checking the DOM if iframe is hidden. Timer is used to wait for 1 second before checking the DOM if its updated

    });
});

function checkiframe(){
    var iframe_flag =jQuery("iframe").is(":visible"); //Flagging if iFrame is Visible
    console.log(iframe_flag);
    var tooglePlay=0;
    if (iframe_flag) {                                //If Visible then AutoPlaying the Video
        tooglePlay=1;
        setTimeout(toogleVideo, 1000);                //Also using timeout here
    }
    if (!iframe_flag) {     
        tooglePlay =0;
        setTimeout(toogleVideo('hide'), 1000);  
    }   
}

function toogleVideo(state) {
    var div = document.getElementsByTagName("iframe")[0].contentWindow;
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    div.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}; 

Also, as a simpler example, check this out on JSFiddle

另外,作为一个更简单的示例,请在JSFiddle检查这个函数

#11


0  

RobW's answers here and elsewhere were very helpful, but I found my needs to be much simpler. I've answered this elsewhere, but perhaps it will be useful here also.

罗柏在这里和其他地方的回答非常有帮助,但我发现我的需要要简单得多。我在别处已经回答过这个问题,但也许它在这里也会有用。

I have a method where I form an HTML string to be loaded in a UIWebView:

我有一种方法,我在UIWebView中生成一个HTML字符串:

NSString *urlString = [NSString stringWithFormat:@"https://www.youtube.com/embed/%@",videoID];

preparedHTML = [NSString stringWithFormat:@"<html><body style='background:none; text-align:center;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>var player; function onYouTubeIframeAPIReady(){player=new YT.Player('player')}</script><iframe id='player' class='youtube-player' type='text/html' width='%f' height='%f' src='%@?rel=0&showinfo=0&enablejsapi=1' style='text-align:center; border: 6px solid; border-radius:5px; background-color:transparent;' rel=nofollow allowfullscreen></iframe></body></html>", 628.0f, 352.0f, urlString];

You can ignore the styling stuff in the preparedHTML string. The important aspects are:

可以忽略preparedHTML字符串中的样式。重要的方面是:

  • Using the API to create the "YT.player" object. At one point, I only had the video in the iFrame tag and that prevented me from referencing the "player" object later with JS.
  • 使用API创建“YT”。球员”对象。在某一时刻,我只有iFrame标记中的视频,这使我无法在以后使用JS引用“player”对象。
  • I've seen a few examples on the web where the first script tag (the one with the iframe_api src tag) is omitted, but I definitely needed that to get this working.
  • 我在web上看到过一些示例,其中省略了第一个脚本标记(带有iframe_api src标记的那个),但我确实需要它来实现这个功能。
  • Creating the "player" variable at the beginning of the API script. I have also seen some examples that have omitted that line.
  • 在API脚本的开头创建“player”变量。我也看到一些例子省略了这一行。
  • Adding an id tag to the iFrame to be referenced in the API script. I almost forgot that part.
  • 向API脚本中要引用的iFrame添加id标记。我差点忘了那部分。
  • Adding "enablejsapi=1" to the end of the iFrame src tag. That hung me up for a while, as I initially had it as an attribute of the iFrame tag, which does not work/did not work for me.
  • 在iFrame src标记的末尾添加“enablejsapi=1”。这让我犹豫了一段时间,因为我最初把它作为iFrame标记的属性,它对我不起作用/不起作用。

When I need to pause the video, I just run this:

当我需要暂停视频时,我就运行这个:

[webView stringByEvaluatingJavaScriptFromString:@"player.pauseVideo();"];

Hope that helps!

希望会有帮助!

#12


0  

This is working fine to me with YT player

这对我来说很好

 createPlayer(): void {
  return new window['YT'].Player(this.youtube.playerId, {
  height: this.youtube.playerHeight,
  width: this.youtube.playerWidth,
  playerVars: {
    rel: 0,
    showinfo: 0
  }
});
}

this.youtube.player.pauseVideo();

this.youtube.player.pauseVideo();

#13


0  

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.

我希望它能对你有所帮助。

#14


0  

A more concise, elegant, and secure answer: add “?enablejsapi=1” to the end of the video URL, then construct and stringify an ordinary object representing the pause command:

一个更简洁,更优雅,更安全的答案:add ?将enablejsapi=1“到视频URL的末尾,然后构造和stringify一个表示暂停命令的普通对象:

const YouTube_pause_video_command_JSON = JSON.stringify(Object.create(null, {
    "event": {
        "value": "command",
        "enumerable": true
    },
    "func": {
        "value": "pauseVideo",
        "enumerable": true
    }
}));

Use the Window.postMessage method to send the resulting JSON string to the embedded video document:

使用窗口。postMessage方法将产生的JSON字符串发送到嵌入式视频文档:

// |iframe_element| is defined elsewhere.
const video_URL = iframe_element.getAttributeNS(null, "src");
iframe_element.contentWindow.postMessage(YouTube_pause_video_command_JSON, video_URL);

Make sure you specify the video URL for the Window.postMessage method’s targetOrigin argument to ensure that your messages won’t be sent to any unintended recipient.

确保为窗口指定视频URL。postMessage方法的targetOrigin参数,以确保您的消息不会被发送到任何无意的收件人。