我试图嵌入新的iframe版本的YouTube视频,并让它自动播放。

据我所知,没有办法通过修改URL的标志来做到这一点。有办法通过使用JavaScript和API来做到这一点吗?


当前回答

现在我在iframe标签上添加了一个新的属性“allow”,例如:

允许= "加速度计;播放;加密介质;陀螺仪; 画中画”

最终代码是:

<iframe src="https://www.youtube.com/embed/[VIDEO-CODE]?autoplay=1" 
frameborder="0" style="width: 100%; height: 100%;"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"></iframe>

其他回答

在iframe src的末尾,添加&enablejsapi=1以允许在视频上使用js API

然后用jquery:

jQuery(document).ready(function( $ ) {
  $('.video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
});

这将在document.ready上自动播放视频

注意,你也可以在点击函数中使用这个来点击另一个元素来启动视频

更重要的是,你不能在移动设备上自动启动视频,所以用户总是要点击视频播放器本身来启动视频

编辑: 从文件上看,我不是百分之百确定。iframe已经准备好了,因为YouTube可能还在加载视频。我实际上是在点击函数中使用这个函数:

$('.video-container').on('click', function(){
  $('video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
  // add other code here to swap a custom image, etc
});

为了让mjhm在2018年5月在Chrome 66上工作,我在iframe中添加了allow=autoplay,并在查询字符串中添加了enable_js=1:

<iframe allow=autoplay width="420px" height="345px" src="http://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&enable_js=1"></iframe>

为那些不知道(过去的我和未来的我)的人提供多个查询提示

如果您只是使用url进行单个查询?autoplay=1工作,如mjhm的答案所示

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1"></iframe>

如果你有多个查询还记得第一个以a开头吗?而其他的则以&开头

假设你想关闭相关视频,但启用自动播放…

这是

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0&autoplay=1"></iframe>

这是可行的

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&rel=0"></iframe>

但是这些都没用。

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0?autoplay=1"></iframe>

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0&autoplay=1&rel=0"></iframe>

例子比较

https://jsfiddle.net/Hastig/p4dpo5y4/

更多信息

有关使用多个查询字符串的更多信息,请阅读下面NextLocal的回复

1 -添加&enablejsapi=1到IFRAME SRC

jQuery func:

  $('iframe#your_video')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');

工作正常

youtube的内嵌代码默认是自动播放的。只需在“src”属性的末尾添加autoplay=1。例如:

<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>