我有一个在<iframe>
中包含YouTube视频的隐藏div。当用户点击一个链接时,这个div变得可见,然后用户应该能够播放视频。
当用户关闭面板时,视频应停止播放。我如何才能做到这一点?
代码:
<!-- link to open popupVid -->
<p><a href="javascript:;" onClick="document.getElementById('popupVid').style.display='';">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
<iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40" frameborder="0" allowfullscreen></iframe>
<br /><br />
<a href="javascript:;" onClick="document.getElementById('popupVid').style.display='none';">
close
</a>
</div><!--end of popupVid -->
发布于 2015-10-24 06:25:18
这是一个简单的jQuery片段,可以根据RobW和DrewT的回答暂停页面上的所有视频:
jQuery("iframe").each(function() {
jQuery(this)[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')
});
发布于 2012-08-18 03:21:10
一个简单的方法是简单地将视频的src设置为空,这样视频就会在隐藏时消失,然后当你点击打开视频的链接时,将src设置回你想要的视频。为此,只需为youtube iframe设置一个id,并使用该id调用src函数,如下所示:
<script type="text/javascript">
function deleteVideo()
{
document.getElementById('VideoPlayer').src='';
}
function LoadVideo()
{
document.getElementById('VideoPlayer').src='http://www.youtube.com/embed/WHAT,EVER,YOUTUBE,VIDEO,YOU,WHANT';
}
</script>
<body>
<p onclick="LoadVideo()">LOAD VIDEO</P>
<p onclick="deleteVideo()">CLOSE</P>
<iframe id="VideoPlayer" width="853" height="480" src="http://www.youtube.com/WHAT,EVER,YOUTUBE,VIDEO,YOU,HAVE" frameborder="0" allowfullscreen></iframe>
</boby>
发布于 2015-04-28 00:18:38
由于在使用other answers中提到的playVideo
/ pauseVideo
命令之前,您需要在iframe的src中设置?enablejsapi=true
,因此通过Javascript以编程方式添加此命令可能会很有用(特别是在以下情况下,例如,.您希望此行为适用于由其他用户嵌入的视频,这些用户刚刚剪切并粘贴了YouTube嵌入代码。在这种情况下,下面这样的代码可能会很有用:
function initVideos() {
// Find all video iframes on the page:
var iframes = $(".video").find("iframe");
// For each of them:
for (var i = 0; i < iframes.length; i++) {
// If "enablejsapi" is not set on the iframe's src, set it:
if (iframes[i].src.indexOf("enablejsapi") === -1) {
// ...check whether there is already a query string or not:
// (ie. whether to prefix "enablejsapi" with a "?" or an "&")
var prefix = (iframes[i].src.indexOf("?") === -1) ? "?" : "&";
iframes[i].src += prefix + "enablejsapi=true";
}
}
}
如果你在document.ready
上调用它,那么在一个类为“...if”的div中的所有iframe都会将enablejsapi=true
添加到它们的源代码中,这样playVideo / pauseVideo命令就可以对它们起作用了。
(注意:本例对设置var iframes
的那一行代码使用了jQuery,但如果您不使用jQuery,一般的方法应该也适用于纯Javascript )。
https://stackoverflow.com/questions/8667882
复制相似问题