停止嵌入式YouTube iframe?

发布于 2025-02-02 19:27:57 字数 717 浏览 4 评论 0原文

我正在使用youtube iframe将视频嵌入我的网站上。

<iframe width="100%" height="443" class="yvideo" id="p1QgNF6J1h0"
              src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
              frameborder="0" allowfullscreen>
</iframe>

而且我在同一页面上有乘以乘以视频。

我想在使用JavaScript左右的单击按钮中停止所有它们或其中一个。

是否可以?

更新:

我尝试了 talvi watia 所说并使用了什么:

$('#myStopClickButton').click(function(){
  $('.yvideo').each(function(){
    $(this).stopVideo();
  });
});

我得到了:

Uncaught TypeError: Object [object Object] has no method 'stopVideo' 

I'm using YouTube iframe to embed videos on my site.

<iframe width="100%" height="443" class="yvideo" id="p1QgNF6J1h0"
              src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
              frameborder="0" allowfullscreen>
</iframe>

And i have multiplie videos on the same page.

I want to stop all of them or one of them in a click of a button using javascript or so.

Is it possible?

UPDATE:

I tried what Talvi Watia said and used:

$('#myStopClickButton').click(function(){
  $('.yvideo').each(function(){
    $(this).stopVideo();
  });
});

I'm getting:

Uncaught TypeError: Object [object Object] has no method 'stopVideo' 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

玉环 2025-02-09 19:27:57

不幸的是,这些API的进化很快。截至2015年5月,拟议的解决方案不再起作用,因为玩家对象没有stopvideo方法。

可以在此页面中找到一个可靠的解决方案( 1 ),它可以使用:

<iframe id="youtube_player" class="yt_player_iframe" width="640" height="360" src="http://www.youtube.com/embed/aHUBlv5_K8Y?enablejsapi=1&version=3&playerapiid=ytplayer"  allowfullscreen="true" allowscriptaccess="always" frameborder="0"></iframe>

和以下JS/jQuery代码:

$('.yt_player_iframe').each(function(){
  this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
});

Unfortunately these API's evolve very fast. As of May 2015, the proposed solutions don't work anymore, as the player object has no stopVideo method.

A reliable solution is to be found in this page (1) and it works with an:

<iframe id="youtube_player" class="yt_player_iframe" width="640" height="360" src="http://www.youtube.com/embed/aHUBlv5_K8Y?enablejsapi=1&version=3&playerapiid=ytplayer"  allowfullscreen="true" allowscriptaccess="always" frameborder="0"></iframe>

and the following JS/jQuery code:

$('.yt_player_iframe').each(function(){
  this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
});
逐鹿 2025-02-09 19:27:57

如果有人仍在寻找答案,我就这样解决了:

$("#photos").on("hide",function(){
    var leg=$('.videoPlayer').attr("src");
    $('.videoPlayer').attr("src",leg);
});

#photos是模态的ID,并且.VideOplayer是IFRAME的类。
基本上,它刷新了SRC属性(并且停止播放视频)。
因此,

    $('#myStopClickButton').click(function(){
      $('.yvideo').each(function(){
        var el_src = $(this).attr("src");
        $(this).attr("src",el_src);
      });
    });

应该解决问题。

If anyone is still looking for the answer, i've solved it like so:

$("#photos").on("hide",function(){
    var leg=$('.videoPlayer').attr("src");
    $('.videoPlayer').attr("src",leg);
});

Where #photos is the ID of the modal and .videoPlayer is the class of the iframe.
Basically it refreshes the src attribute (and stops playing the video).
So,

    $('#myStopClickButton').click(function(){
      $('.yvideo').each(function(){
        var el_src = $(this).attr("src");
        $(this).attr("src",el_src);
      });
    });

should do the trick.

無心 2025-02-09 19:27:57

这是 codepen ,它对我有用。

我正在寻找将YT视频嵌入iframe中的最简单解决方案,我觉得就是这样。

我需要的是将视频出现在模式窗口中, stop 播放它在关闭时

是代码:( from: https://codepen.io/anon/pen/gbjqqr

    <div><a href="#" class="play-video">Play Video</a></div>
    <div><a href="#" class="stop-video">Stop Video</a></div>
    <div><a href="#" class="pause-video">Pause Video</a></div>

    <iframe class="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/glEiPXAYE-U?enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>

$('a.play-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'playVideo' + '","args":""}', '*');
});

$('a.stop-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
});

$('a.pause-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
});

此外在尚不可见的dom-object中,例如模态窗口,如果我使用相同的按钮播放我用来显示模式的视频,它将无法使用,所以我使用了以下内容:

https://www.youtube.com/embed/EzAGZCPSOfg?autoplay=1&enablejsapi=1&version=3&playerapiid=ytplayer

注意:?autoplay = 1&amp;放置在何处以及使用'&amp;'在下一个属性之前,允许暂停继续工作。

Here is a codepen, it worked for me.

I was searching for the simplest solution for embedding the YT video within an iframe, and I feel this is it.

What I needed was to have the video appear in a modal window and stop playing when it was closed

Here is the code : (from: https://codepen.io/anon/pen/GBjqQr)

    <div><a href="#" class="play-video">Play Video</a></div>
    <div><a href="#" class="stop-video">Stop Video</a></div>
    <div><a href="#" class="pause-video">Pause Video</a></div>

    <iframe class="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/glEiPXAYE-U?enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>

$('a.play-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'playVideo' + '","args":""}', '*');
});

$('a.stop-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
});

$('a.pause-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
});

Additionally, if you want it to autoplay in a DOM-object that is not yet visible, such as a modal window, if I used the same button to play the video that I was using to show the modal it would not work so I used THIS:

https://www.youtube.com/embed/EzAGZCPSOfg?autoplay=1&enablejsapi=1&version=3&playerapiid=ytplayer

Note: The ?autoplay=1& where it's placed and the use of the '&' before the next property to allow the pause to continue to work.

时光磨忆 2025-02-09 19:27:57

您可能需要通过 youtube javascript api 参考文档。

当您将视频嵌入页面上时,您将需要传递此参数:

http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1

如果要停止所有视频按钮,则可以设置JavaScript例程以循环浏览视频并停止它们:

player.stopVideo()

这确实涉及跟踪跟踪页面上每个视频的所有页面ID。更简单的可能是上课,然后使用jquery.east。

$('#myStopClickButton').click(function(){
  $('.myVideoClass').each(function(){
    $(this).stopVideo();
  });
});

You may want to review through the Youtube JavaScript API Reference docs.

When you embed your video(s) on the page, you will need to pass this parameter:

http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1

If you want a stop all videos button, you can setup a javascript routine to loop through your videos and stop them:

player.stopVideo()

This does involve keeping track of all the page IDs for each video on the page. Even simpler might be to make a class and then use jQuery.each.

$('#myStopClickButton').click(function(){
  $('.myVideoClass').each(function(){
    $(this).stopVideo();
  });
});
他不在意 2025-02-09 19:27:57

API是凌乱的,因为它们不断变化。这种纯粹的JavaScript方式对我有用:

 <div id="divScope" class="boom-lightbox" style="display: none;">
    <iframe id="ytplayer" width="720" height="405"   src="https://www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen>    </iframe>
  </div>  

//if I want i can set scope to a specific region
var myScope = document.getElementById('divScope');      
//otherwise set scope as the entire document
//var myScope = document;

//if there is an iframe inside maybe embedded multimedia video/audio, we should reload so it stops playing
var iframes = myScope.getElementsByTagName("iframe");
if (iframes != null) {
    for (var i = 0; i < iframes.length; i++) {
        iframes[i].src = iframes[i].src; //causes a reload so it stops playing, music, video, etc.
    }
}

APIs are messy because they keep changing. This pure javascript way worked for me:

 <div id="divScope" class="boom-lightbox" style="display: none;">
    <iframe id="ytplayer" width="720" height="405"   src="https://www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen>    </iframe>
  </div>  

//if I want i can set scope to a specific region
var myScope = document.getElementById('divScope');      
//otherwise set scope as the entire document
//var myScope = document;

//if there is an iframe inside maybe embedded multimedia video/audio, we should reload so it stops playing
var iframes = myScope.getElementsByTagName("iframe");
if (iframes != null) {
    for (var i = 0; i < iframes.length; i++) {
        iframes[i].src = iframes[i].src; //causes a reload so it stops playing, music, video, etc.
    }
}
皓月长歌 2025-02-09 19:27:57

Talvi的答案可能仍然有效,但是YouTube JavaScript API已被标记为弃用。现在,您应该使用新的 youtube iframe api

该文档提供了几种完成视频嵌入的方法,但是为了您的目标,您将包括以下内容:

//load the IFrame Player API code asynchronously
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//will be youtube player references once API is loaded
var players = [];

//gets called once the player API has loaded
function onYouTubeIframeAPIReady() {
    $('.myiframeclass').each(function() {
        var frame = $(this);

        //create each instance using the individual iframe id
        var player = new YT.Player(frame.attr('id'));

        players.push(player);
    });
}

//global stop button click handler
$('#mybutton').click(function(){

    //loop through each Youtube player instance and call stopVideo()
    for (var i in players) {
        var player = players[i];
        player.stopVideo();
    }
});

Talvi's answer may still work, but that Youtube Javascript API has been marked as deprecated. You should now be using the newer Youtube IFrame API.

The documentation provides a few ways to accomplish video embedding, but for your goal, you'd include the following:

//load the IFrame Player API code asynchronously
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//will be youtube player references once API is loaded
var players = [];

//gets called once the player API has loaded
function onYouTubeIframeAPIReady() {
    $('.myiframeclass').each(function() {
        var frame = $(this);

        //create each instance using the individual iframe id
        var player = new YT.Player(frame.attr('id'));

        players.push(player);
    });
}

//global stop button click handler
$('#mybutton').click(function(){

    //loop through each Youtube player instance and call stopVideo()
    for (var i in players) {
        var player = players[i];
        player.stopVideo();
    }
});
海拔太高太耀眼 2025-02-09 19:27:57

最简单的方法是

var frame = document.getElementById("iframeid");
frame.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');

Easiest ways is

var frame = document.getElementById("iframeid");
frame.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
沉鱼一梦 2025-02-09 19:27:57

一个人不能简单地高估这篇文章并回答thx op和助手。
我的解决方案仅通过Video_ID交换:

<div style="pointer-events: none;">
    <iframe id="myVideo" src="https://www.youtube.com/embed/video_id?rel=0&modestbranding=1&fs=0&controls=0&autoplay=1&showinfo=0&version=3&enablejsapi=1" width="560" height="315" frameborder="0"></iframe> </div>

    <button id="play">PLAY</button>

    <button id="pause">PAUSE</button>


    <script>
        $('#play').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                    '{"event":"command","func":"playVideo","args":""}', 
                    '*'); 
            });
        });

        $('#pause').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                  '{"event":"command","func":"pauseVideo","args":""}',
                  '*'); 
            });
        });
    </script>

One cannot simply overestimate this post and answers thx OP and helpers.
My solution with just video_id exchanging:

<div style="pointer-events: none;">
    <iframe id="myVideo" src="https://www.youtube.com/embed/video_id?rel=0&modestbranding=1&fs=0&controls=0&autoplay=1&showinfo=0&version=3&enablejsapi=1" width="560" height="315" frameborder="0"></iframe> </div>

    <button id="play">PLAY</button>

    <button id="pause">PAUSE</button>


    <script>
        $('#play').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                    '{"event":"command","func":"playVideo","args":""}', 
                    '*'); 
            });
        });

        $('#pause').click(function() {
            $('#myVideo').each(function(){ 
                var frame = document.getElementById("myVideo");
                frame.contentWindow.postMessage(
                  '{"event":"command","func":"pauseVideo","args":""}',
                  '*'); 
            });
        });
    </script>
物价感观 2025-02-09 19:27:57

这是我发现的最直接的解决方案。

  1. 非常重要!添加?enablejsapi = 1参数到iframe src属性。例如scr =“ https://youtube.com/embed/video_id?enablejsapi=1

  2. var iframe = document.queryselector('iframe'';; 或您想掌握该元素。

  3. iframe.contentwindow.postmessage('{“ event”:“命令”,“ func”:“ pausevideo”,“ args”:“”}'}'}','*');

本质上,此代码是持有YouTube Player对象,该对象包含在&lt; Iframe&gt;元素中。参见“ noreferrer”> htmliframeement.contentwindowwindowwindowwindowwindowwindow “ https://developer.mozilla.org/en-us/docs/web/api/window/postmessage” rel =“ noreferrer”> postmessage()。最后,Google提供了JavaScript API参考在这里用于所有可用功能。

This is the most straightforward solution that I have found.

  1. Very important! Add ?enablejsapi=1 parameter to the iframe src attribute. E.g. scr="https://youtube.com/embed/VIDEO_ID?enablejsapi=1

  2. var iframe = document.querySelector('iframe'); or however you want to get a hold of the element.

  3. iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');

Essentially, this code is getting a hold of the Youtube Player object which is contained within the <iframe> element. See HTMLIFrameElement.contentWindow on MDN and postMessage(). Finally, Google provides a Javascript API reference here for all available functions.

表情可笑 2025-02-09 19:27:57

对于带有视频的Twitter Bootstrap模态/弹出窗口,这对我有用:

$('.modal.stop-video-on-close').on('hidden.bs.modal', function(e) {
  $('.video-to-stop', this).each(function() {
    this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div id="vid" class="modal stop-video-on-close"
  tabindex="-1" role="dialog" aria-labelledby="Title">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
        <h4 class="modal-title">Title</h4>
      </div>
      <div class="modal-body">
       <iframe class="video-to-stop center-block"
        src="https://www.youtube.com/embed/3q4LzDPK6ps?enablejsapi=1&rel=0"
        allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
        frameborder="0" allowfullscreen>
       </iframe>
      </div>
      <div class="modal-footer">
        <button class="btn btn-danger waves-effect waves-light"
          data-dismiss="modal" type="button">Close</button>
      </div>
    </div>
  </div>
</div>

<button class="btn btn-success" data-toggle="modal"
 data-target="#vid" type="button">Open video modal</button>

基于 marco的答案,请注意,我只需要添加enablejsapi = 1 parameter视频URL(rel = 0只是为了在最后不显示相关的视频)。 JS 后Message功能是所有繁重的举重,实际上会阻止视频。

该片段可能由于要求权限而无法显示视频,但是在常规浏览器中,截至2018年11月,该视频应起作用。

For a Twitter Bootstrap modal/popup with a video inside, this worked for me:

$('.modal.stop-video-on-close').on('hidden.bs.modal', function(e) {
  $('.video-to-stop', this).each(function() {
    this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div id="vid" class="modal stop-video-on-close"
  tabindex="-1" role="dialog" aria-labelledby="Title">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
        <h4 class="modal-title">Title</h4>
      </div>
      <div class="modal-body">
       <iframe class="video-to-stop center-block"
        src="https://www.youtube.com/embed/3q4LzDPK6ps?enablejsapi=1&rel=0"
        allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
        frameborder="0" allowfullscreen>
       </iframe>
      </div>
      <div class="modal-footer">
        <button class="btn btn-danger waves-effect waves-light"
          data-dismiss="modal" type="button">Close</button>
      </div>
    </div>
  </div>
</div>

<button class="btn btn-success" data-toggle="modal"
 data-target="#vid" type="button">Open video modal</button>

Based on Marco's answer, notice that I just needed to add the enablejsapi=1 parameter to the video URL (rel=0 is just for not displaying related videos at the end). The JS postMessage function is what does all the heavy lifting, it actually stops the video.

The snippet may not display the video due to request permissions, but in a regular browser this should work as of November of 2018.

纵山崖 2025-02-09 19:27:57

这是一个纯JavaScript解决方案,

<iframe 
width="100%" 
height="443" 
class="yvideo" 
id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0" 
allowfullscreen>
</iframe>
<button id="myStopClickButton">Stop</button>


<script>
document.getElementById("myStopClickButton").addEventListener("click",    function(evt){
var video = document.getElementsByClassName("yvideo");
for (var i=0; i<video.length; i++) {
   video.item(i).contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}

});

Here's a pure javascript solution,

<iframe 
width="100%" 
height="443" 
class="yvideo" 
id="p1QgNF6J1h0"
src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
frameborder="0" 
allowfullscreen>
</iframe>
<button id="myStopClickButton">Stop</button>


<script>
document.getElementById("myStopClickButton").addEventListener("click",    function(evt){
var video = document.getElementsByClassName("yvideo");
for (var i=0; i<video.length; i++) {
   video.item(i).contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');
}

});

饭团 2025-02-09 19:27:57

我们如何暂停/停止YouTube iframe到我们使用ModalPopup中的嵌入视频时

 $('#close_one').click(function (e) {
         
         
         let link = document.querySelector('.divclass');// get iframe class 
         let link = document.querySelector('#divid');// get iframe id
         let video_src = link.getAttribute('src');

         $('.youtube-video').children('iframe').attr('src', ''); // set iframe parent div value null 
         $('.youtube-video').children('iframe').attr('src', video_src);// set iframe src again it works perfect

     });

How we Pause/stop YouTube iframe to when we use embed videos in modalpopup

 $('#close_one').click(function (e) {
         
         
         let link = document.querySelector('.divclass');// get iframe class 
         let link = document.querySelector('#divid');// get iframe id
         let video_src = link.getAttribute('src');

         $('.youtube-video').children('iframe').attr('src', ''); // set iframe parent div value null 
         $('.youtube-video').children('iframe').attr('src', video_src);// set iframe src again it works perfect

     });
樱娆 2025-02-09 19:27:57

这是我使用更新的YouTube API的解决方案。包括开始,停止,暂停。

https://codesandbox.io/s/s/s/s/s/s/youtube-video-video-video-player-player-73x4b

here is my solution using updated youtube API. Includes start, stop, pause.

https://codesandbox.io/s/youtube-video-player-73x4b

祁梦 2025-02-09 19:27:57

另请参见当您留下选项卡视图或最小化离子应用程序时,如何暂停或停止iFrame youtube视频

$scope.stopVideo = function() {
 var iframe = document.getElementsByTagName("iframe")[0].contentWindow;
 iframe.postMessage('{"event":"command","func":"'+'stopVideo'+   '","args":""}', '*');
 }

see also How to pause or stop an iframe youtube video when you leave a tab view or minimise your Ionic App

$scope.stopVideo = function() {
 var iframe = document.getElementsByTagName("iframe")[0].contentWindow;
 iframe.postMessage('{"event":"command","func":"'+'stopVideo'+   '","args":""}', '*');
 }
初与友歌 2025-02-09 19:27:57
$('#aboutVideo .close').on('click',function(){
			var reSrc = $('.aboutPlayer').attr("src");
			$('.aboutPlayer').attr("src",reSrc)
		})
#aboutVideo{
	width: 100%;
	height: 100%;
}
#aboutVideo .modal-dialog, #aboutVideo .modal-dialog .modal-content, #aboutVideo .modal-dialog .modal-content .modal-body{
	width: 100%;
	height: 100%;
	margin: 0 !important;
	padding: 0 !important;
}
#aboutVideo .modal-header{
	padding: 0px; 
	border-bottom: 0px solid #e5e5e5; 
	position: absolute;
	right: 4%;
	top: 4%;
}
#aboutVideo .modal-header .close{
	opacity: 1;
	position: absolute;
	z-index: 99;
	color: #fff;
}
#aboutVideo .modal-header button.close{
      border-radius: 50%;
    width: 7vw;
    height: 7vw;
    position: absolute;
    right: 4%;
    top: 7%;
    background: aliceblue;
}
#aboutVideo .modal-header button.close:hover{
	background-color: rgba(255, 255, 255, 0.28);
}
#aboutVideo .modal-header button.close img{
	width: 20px;
	margin-top: -0.2vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<li class="see-video fa" type="button" data-toggle="modal" data-target="#aboutVideo">
			<label>SEE VIDEO</label>
		</li>
<div class="modal fade" id="aboutVideo" tabindex="-1" role="dialog" aria-labelledby="aboutVideoLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><img src="http://www.freeiconspng.com/uploads/white-close-button-png-16.png"></span></button>
				</div>
				<div class="modal-body">
				<iframe class="aboutPlayer" width="100%" height="100%" src="https://www.youtube.com/embed/fju9ii8YsGs?autoplay=0&showinfo=0&controls=2&rel=0" frameborder="0" allowfullscreen poster="https://www.google.co.in/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwiOvaagmqfWAhUHMY8KHUuJCnkQjRwIBw&url=http%3A%2F%2Fnodeframework.com%2F&psig=AFQjCNEaHveDtZ81veNPSvQDx4IqaE_Tzw&ust=1505565378467268"></iframe>
				</div>
			</div>
		</div>
	</div>

$('#aboutVideo .close').on('click',function(){
			var reSrc = $('.aboutPlayer').attr("src");
			$('.aboutPlayer').attr("src",reSrc)
		})
#aboutVideo{
	width: 100%;
	height: 100%;
}
#aboutVideo .modal-dialog, #aboutVideo .modal-dialog .modal-content, #aboutVideo .modal-dialog .modal-content .modal-body{
	width: 100%;
	height: 100%;
	margin: 0 !important;
	padding: 0 !important;
}
#aboutVideo .modal-header{
	padding: 0px; 
	border-bottom: 0px solid #e5e5e5; 
	position: absolute;
	right: 4%;
	top: 4%;
}
#aboutVideo .modal-header .close{
	opacity: 1;
	position: absolute;
	z-index: 99;
	color: #fff;
}
#aboutVideo .modal-header button.close{
      border-radius: 50%;
    width: 7vw;
    height: 7vw;
    position: absolute;
    right: 4%;
    top: 7%;
    background: aliceblue;
}
#aboutVideo .modal-header button.close:hover{
	background-color: rgba(255, 255, 255, 0.28);
}
#aboutVideo .modal-header button.close img{
	width: 20px;
	margin-top: -0.2vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<li class="see-video fa" type="button" data-toggle="modal" data-target="#aboutVideo">
			<label>SEE VIDEO</label>
		</li>
<div class="modal fade" id="aboutVideo" tabindex="-1" role="dialog" aria-labelledby="aboutVideoLabel">
		<div class="modal-dialog" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><img src="http://www.freeiconspng.com/uploads/white-close-button-png-16.png"></span></button>
				</div>
				<div class="modal-body">
				<iframe class="aboutPlayer" width="100%" height="100%" src="https://www.youtube.com/embed/fju9ii8YsGs?autoplay=0&showinfo=0&controls=2&rel=0" frameborder="0" allowfullscreen poster="https://www.google.co.in/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwiOvaagmqfWAhUHMY8KHUuJCnkQjRwIBw&url=http%3A%2F%2Fnodeframework.com%2F&psig=AFQjCNEaHveDtZ81veNPSvQDx4IqaE_Tzw&ust=1505565378467268"></iframe>
				</div>
			</div>
		</div>
	</div>

北方的韩爷 2025-02-09 19:27:57

与打字稿反应的解决方案


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":"stopVideo","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}
  />
)}

Solution for React with TypeScript


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":"stopVideo","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}
  />
)}
国际总奸 2025-02-09 19:27:57
var vid_element = $('.youtube-player');
vid_element.detach();
$('#parent').append(vid_element);

我发现独立式,然后附加元素比重新分配SRC属性更可靠。

var vid_element = $('.youtube-player');
vid_element.detach();
$('#parent').append(vid_element);

I find detaching and then appending the element more reliable than re-assigning the src attribute.

清秋悲枫 2025-02-09 19:27:57

有一种非常简单的方法可以实现
如果您在JS中

  
 function pauseVideo(){
 document.getElementById("myVideoId").contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');  

 } 
<!DOCTYPE html>
<html>
<body>

<iframe id="myVideoId" src="https://www.youtube.com/embed/Q63qjIXMqwU?enablejsapi=1"></iframe> 
<button onclick = {pauseVideo()}>Pause</button>




</body>
</html>

如果您正在使用react js

export const VideoPlayer = () =>{
 const videoooo = useRef();
  const pauseVideo = () => {
  //at the place of pauseVideo you can use "stopVideo", "playVideo"
videoooo.current.contentWindow.postMessage(
      '{"event":"command","func":"pauseVideo","args":""}',
      "*"
    );
  };

return(<> <iframe
        ref={videoooo}
        id="myVideoId"
        src="https://www.youtube.com/embed/Q63qjIXMqwU?enablejsapi=1"
      ></iframe>
      <button
        onClick={() => {
          pauseVideo();
        }}
      >
        Pause
      </button></>)
}

There is a very easy way to achieve
if you are in JS

  
 function pauseVideo(){
 document.getElementById("myVideoId").contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');  

 } 
<!DOCTYPE html>
<html>
<body>

<iframe id="myVideoId" src="https://www.youtube.com/embed/Q63qjIXMqwU?enablejsapi=1"></iframe> 
<button onclick = {pauseVideo()}>Pause</button>




</body>
</html>

if you are using react js

export const VideoPlayer = () =>{
 const videoooo = useRef();
  const pauseVideo = () => {
  //at the place of pauseVideo you can use "stopVideo", "playVideo"
videoooo.current.contentWindow.postMessage(
      '{"event":"command","func":"pauseVideo","args":""}',
      "*"
    );
  };

return(<> <iframe
        ref={videoooo}
        id="myVideoId"
        src="https://www.youtube.com/embed/Q63qjIXMqwU?enablejsapi=1"
      ></iframe>
      <button
        onClick={() => {
          pauseVideo();
        }}
      >
        Pause
      </button></>)
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文