62

我正在使用 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' 
4

15 回答 15

104

不幸的是,这些 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":""}', '*')
});
于 2015-05-20T18:47:53.073 回答
38

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

$("#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);
      });
    });

应该做的伎俩。

于 2016-03-30T15:20:46.510 回答
19

您可能需要查看Youtube JavaScript API参考文档。

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

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

如果您想要停止所有视频按钮,您可以设置一个 javascript 例程来循环播放视频并停止它们:

player.stopVideo()

这确实涉及跟踪页面上每个视频的所有页面 ID。更简单的可能是创建一个类,然后使用 jQuery.each。

$('#myStopClickButton').click(function(){
  $('.myVideoClass').each(function(){
    $(this).stopVideo();
  });
});
于 2013-03-01T19:15:29.643 回答
19

这是一个codepen,它对我有用。

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

我需要的是让视频出现在模式窗口中并在关闭时停止播放

这是代码:(来自: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 对象(例如模态窗口)中自动播放,如果我使用相同的按钮来播放用于显示模态的视频,它将无法正常工作,所以我使用了这个:

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

注意:?autoplay=1&它的放置位置以及在下一个属性之前使用“&”以允许暂停继续工作。

于 2018-07-18T16:39:12.457 回答
16

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.
    }
}
于 2016-04-21T23:42:44.307 回答
14

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();
    }
});
于 2015-03-23T20:53:04.413 回答
7

不能简单地高估这篇文章并回答 thx OP 和 helpers。我的解决方案只有 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>
于 2017-09-13T10:35:43.517 回答
6

最简单的方法是

var frame = document.getElementById("iframeid");
frame.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
于 2017-03-18T15:52:23.523 回答
4

对于内部带有视频的 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">&times;</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参数添加到视频 URL(rel=0只是为了不显示最后的相关视频)。JSpostMessage函数完成了所有繁重的工作,它实际上停止了视频。

由于请求权限,该片段可能不会显示视频,但在常规浏览器中,这应该可以在 2018 年 11 月开始使用。

于 2018-11-20T11:59:38.443 回答
3

这是一个纯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":""}', '*');
}

});

于 2018-10-10T11:44:47.060 回答
2

当我们在模态弹出窗口中使用嵌入视频时,我们如何暂停/停止 YouTube iframe

 $('#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

     });
于 2020-09-04T04:52:25.340 回答
1

$('#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>

于 2017-09-15T12:41:09.457 回答
1

另请参阅当您离开选项卡视图或最小化 Ionic 应用程序时如何暂停或停止 iframe youtube 视频

$scope.stopVideo = function() {
 var iframe = document.getElementsByTagName("iframe")[0].contentWindow;
 iframe.postMessage('{"event":"command","func":"'+'stopVideo'+   '","args":""}', '*');
 }
于 2016-02-01T05:14:33.840 回答
1

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

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

于 2022-01-12T11:03:05.200 回答
0
var vid_element = $('.youtube-player');
vid_element.detach();
$('#parent').append(vid_element);

我发现分离然后附加元素比重新分配 src 属性更可靠。

于 2022-02-20T11:21:43.780 回答