我试图嵌入新的iframe版本的YouTube视频,并让它自动播放。
据我所知,没有办法通过修改URL的标志来做到这一点。有办法通过使用JavaScript和API来做到这一点吗?
我试图嵌入新的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 allow="autoplay *; fullscreen *" allowfullscreen="true"
src="https://example.com">
</iframe>
&如果你想惰性加载YouTube视频完全使用这个-
<iframe
srcdoc="<style>*{padding:0;margin:0;overflow:hidden}html,body{height:100%}img,span{position:absolute;width:100%;top:0;bottom:0;margin:auto}span{height:1.5em;text-align:center;font:48px/1.5 sans-serif;color:white;text-shadow:0 0 0.5em black}</style><a href=https://www.youtube.com/embed/unICbsPGFIA?autoplay=1><img src=https://img.youtube.com/vi/zEkgWzi5T-Y/hqdefault.jpg><span>▶</span></a>"
src="https://www.youtube.com/embed/unICbsPGFIA?autoplay=1&loop=1&playlist=zEkgWzi5T-Y"
frameborder="0"
allow="accelerometer; autoplay *; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
1 -添加&enablejsapi=1到IFRAME SRC
jQuery func:
$('iframe#your_video')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
工作正常
自2018年4月起,谷歌对自动播放政策进行了一些更改。你不仅需要添加autoplay=1作为查询参数,还需要添加allow='autoplay'作为iframe的属性
所以你必须这样做:
<iframe src="https://www.youtube.com/embed/VIDEO_ID?autoplay=1" allow='autoplay'></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
});
<iframe width="560" height="315"
src="https://www.youtube.com/embed/9IILMHo4RCQ?rel=0&controls=0&showinfo=0&autoplay=1"
frameborder="0" allowfullscreen></iframe>