Html 停止嵌入式 YouTube iframe?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15164942/
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
Stop embedded youtube iframe?
提问by Danpe
I'm using YouTube iframe to embed videos on my site.
我正在使用 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>
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.
我想使用 javascript 左右单击一个按钮来停止所有这些或其中一个。
Is it possible?
是否可以?
UPDATE:
更新:
I tried what Talvi Watiasaid and used:
我尝试了Talvi Watia所说和使用的内容:
$('#myStopClickButton').click(function(){
$('.yvideo').each(function(){
$(this).stopVideo();
});
});
I'm getting:
我越来越:
Uncaught TypeError: Object [object Object] has no method 'stopVideo'
采纳答案by Talvi Watia
You may want to review through the Youtube JavaScript APIReference docs.
您可能需要查看Youtube JavaScript API参考文档。
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:
如果您想要停止所有视频按钮,您可以设置一个 javascript 例程来循环播放您的视频并停止它们:
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.
这确实涉及跟踪页面上每个视频的所有页面 ID。更简单的可能是创建一个类,然后使用 jQuery.each。
$('#myStopClickButton').click(function(){
$('.myVideoClass').each(function(){
$(this).stopVideo();
});
});
回答by Marco Faustinelli
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.
不幸的是,这些 API 的发展非常快。截至 2015 年 5 月,提议的解决方案不再有效,因为玩家对象没有stopVideo
方法。
A reliable solution is to be found in this page (1) and it works with an:
在此页面 ( 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>
and the following JS/jQuery code:
以及以下 JS/jQuery 代码:
$('.yt_player_iframe').each(function(){
this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
});
回答by Jax297
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,
其中 #photos 是模态的 ID, .videoPlayer 是 iframe 的类。基本上它会刷新 src 属性(并停止播放视频)。所以,
$('#myStopClickButton').click(function(){
$('.yvideo').each(function(){
var el_src = $(this).attr("src");
$(this).attr("src",el_src);
});
});
should do the trick.
应该做的伎俩。
回答by JJ_Coder4Hire
APIs are messy because they keep changing. This pure javascript way worked for me:
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.
}
}
回答by HotN
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.
Talvi 的答案可能仍然有效,但 Youtube Javascript API 已被标记为已弃用。您现在应该使用较新的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();
}
});
回答by namretiolnave
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.
我正在寻找在 iframe 中嵌入 YT 视频的最简单的解决方案,我觉得就是这样。
What I needed was to have the video appear in a modal window and stopplaying when it was closed
我需要的是让视频出现在模态窗口中并在关闭时停止播放
Here is the code : (from: https://codepen.io/anon/pen/GBjqQr)
这是代码:(来自: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, ifyou want it to autoplayin 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:
此外,如果您希望它在尚不可见的 DOM 对象(例如模态窗口)中自动播放,如果我使用相同的按钮来播放我用来显示模态的视频,它将无法工作,所以我使用这个:
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.
注意:?autoplay=1&
放置它的位置以及在 next 属性之前使用“&”以允许暂停继续工作。
回答by Aleksander Dudek
One cannot simply overestimate this post and answers thx OP and helpers. My solution with just video_id exchanging:
不能简单地高估这篇文章并回答 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>
回答by imal hasaranga perera
Easiest ways is
最简单的方法是
var frame = document.getElementById("iframeid");
frame.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
回答by CPHPython
For a Twitter Bootstrap modal/popup with a video inside, this worked for me:
对于带有视频的 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>
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.
根据Marco 的回答,请注意我只需要将enablejsapi=1
参数添加到视频 URL(rel=0
只是为了在最后不显示相关视频)。JSpostMessage
函数完成了所有繁重的工作,它实际上停止了视频。
The snippet may not display the video due to request permissions, but in a regular browser this should work as of November of 2018.
由于请求权限,该代码段可能不会显示视频,但在常规浏览器中,这应该可以在 2018 年 11 月使用。
回答by pingle60
Here's a pure javascript solution,
这是一个纯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":""}', '*');
}
});