Javascript用YouTube视频代替IMG -自动播放不能正常工作

Javascript to replace IMG with YouTube video - Autoplay not working as it should

本文关键字:常工作 不能 工作 自动播放 YouTube 视频 IMG Javascript      更新时间:2023-09-26

我有一张图片,当你点击它时,它会被隐藏,YouTube视频会显示。

我想视频播放时,你点击图像,所以我已经设置了一个参数在YT链接,所以它自动播放,这工作在每个浏览器测试,除了谷歌Chrome。

关于为什么Chrome在我点击图像之前自动播放视频的任何想法?

 <div id="youtube" style="display:none;">
 <iframe width="940" height="520" src="http://www.youtube.com/embed/kr-oMG6EYSs?rel=0&showinfo=0&autoplay=1" wmode="transparent" frameborder="0" allowfullscreen></iframe>
 </div>

 <img src="images/slider_worklife_top.jpg" width="942" height="521" id="imageID" />
 <script type="text/javascript">
 $('#imageID').click(function() {
 $('#youtube').show();
 $('#imageID').hide();
 });
 </script>

尝试用$(function(){/* code */}包装你的JS代码

如果没有帮助,那就尝试一些不同的东西,不要浪费你的时间:):

<div id="youtube" style="display:none;">
   <iframe width="940" height="520" src="" wmode="transparent" frameborder="0" allowfullscreen></iframe>
 </div>
<img src="images/slider_worklife_top.jpg" width="942" height="521" id="imageID" />
<script type="text/javascript">
$(function(){
  $('#imageID').click(function() {
    $('#youtube').show().find("iframe").attr("src","http://www.youtube.com/embed/kr-oMG6EYSs?rel=0&showinfo=0&autoplay=1");
    $('#imageID').hide();
  });
});
</script>

嵌入源配置为自动播放,隐藏容器div不做任何事情(至少在理论上,可能浏览器不同于Chrome不允许iframe执行)。

解决方案是从页面中完全删除iframe,并在需要时将其附加到容器内的页面。

var yt = $('#youtube');
// If you cant store the html directly
var ythtml = yt.html();
yt.hide().children().remove();
// load iframe once needed
$('#imageID').click(function(){
  $(this).hide();
  yt.html(ythtml).show();
});

当然有一个真正的解决方案:使用YT的api。