在 JavaScript 中隐藏/显示 - 停止播放 YouTube iframe 视频
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8931798/
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
Hide/show in JavaScript - stop playing YouTube iframe video
提问by Sabine Quardon
I've used the iframe function to embed videos, and I'm hiding/showing the content and videos through JavaScript.
我已经使用 iframe 函数嵌入视频,并且我正在通过 JavaScript 隐藏/显示内容和视频。
I have oneproblem. When I press play on the first video, and then click on the next without stopping the first one, the first one just keeps on playing.
我有一个问题。当我在第一个视频上按播放键,然后在不停止第一个视频的情况下单击下一个视频,第一个视频会继续播放。
What can I do to stop the video in the "background", when showing new content?
显示新内容时,如何在“背景”中停止视频?
$(function(){
$("#link1").click(show1);
});
function show1(){
$("#pic1").fadeIn();
$("#pic2").hide();
}
I'm just using this simple JavaScript function, where the "pic1" and "pic2" id is the id of the div, the video are embedded in.
我只是使用这个简单的 JavaScript 函数,其中“pic1”和“pic2”id 是 div 的 id,视频被嵌入其中。
I just can't seem to make it work. I tried to put remove, but then you can't see the video again if you want to.
我似乎无法让它发挥作用。我试图删除,但如果你愿意,你就不能再看到视频了。
回答by Rob W
This is an implementation of the YouTube player API, without loading additional files. To get this work, you have to suffix all of your <iframe>
's src
attribute with ?enablejsapi=1
.
这是 YouTube 播放器 API 的实现,无需加载其他文件。要完成这项工作,您必须为您<iframe>
的所有src
属性添加后缀?enablejsapi=1
.
Example (I broke the code over a few lines for readability, you can safely omit the linebreaks):
示例(为了便于阅读,我将代码分成几行,您可以安全地省略换行符):
<div id="pic3">
<iframe width="640" height="390"
src="http://www.youtube.com/embed/Xub4grFLbQM?enablejsapi=1"
frameborder="0" allowfullscreen></iframe>
</div>
<div id="tS2" class="jThumbnailScroller">
.. Removed your code for readability....
<a href="#vid3" id="link3"><img src="images/thumbs/player2.jpg" height="85"/></a>
....
JavaScript + jQuery code:
JavaScript + jQuery 代码:
$(function() {
/* elt: Optionally, a HTMLIFrameElement. This frame's video will be played,
* if possible. Other videos will be paused*/
function playVideoAndPauseOthers(frame) {
$('iframe[src*="http://www.youtube.com/embed/"]').each(function(i) {
var func = this === frame ? 'playVideo' : 'pauseVideo';
this.contentWindow.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
});
}
$('#tS2 a[href^="#vid"]').click(function() {
var frameId = /#vid(\d+)/.exec($(this).attr('href'));
if (frameId !== null) {
frameId = frameId[1]; // Get frameId
playVideoAndPauseOthers($('#pic' + frameId + ' iframe')[0]);
}
});
});