问题
I've used the iframe function to embed videos, and I'm hiding/showing the content and videos through JavaScript.
I have one problem. 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.
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.
回答1:
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
.
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:
$(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]);
}
});
});
来源:https://stackoverflow.com/questions/8931798/hide-show-in-javascript-stop-playing-youtube-iframe-video