javascript - 通过简单的 JS 强制 iframe 自动播放
问题描述
我有一个示例视频,它是用户将视频从 youtube 拖到轻量级 CMS 的页面块中的结果。该视频在界面结果上显示良好,但即使从 YouTube API 中选择了自动播放,也没有自动播放。
有没有办法,可能通过 JS,我可以将页面上的任何 iframe 设置为在 youtube API 选项不起作用的情况下自动播放?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p><iframe src="//www.youtube.com/embed/id?start=1" width="560" height="315" frameborder="0"; autoplay; allowfullscreen="allowfullscreen"></iframe></p>
</body>
</html>
解决方案
这样您就可以自动播放来自 YT 的视频
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'p2FZvPLWf_M',
playerVars: { 'autoplay': 1, 'controls': 1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
//setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
推荐阅读
- objective-c - 如何将 NULL 附加到 char 数组中?
- git - user@ip:权限被拒绝(公钥)。?
- http - 最大注册的 HTTP 状态代码
- airflow - 调度程序未添加动态 dag
- unity3d - 我们如何在 AR 基础 (ARKit3) 中跟踪面部但不将前置摄像头显示到设备屏幕上?
- python - 使用 Airflow 从 S3 进行批处理
- django - Django - 加入特定列
- javascript - TypeScript 在生成的 JavaScript 中列出了导入的接口和类型
- django - 是否需要将社交访问令牌与社交身份验证中的社交电子邮件 ID 进行比较?
- vba - 运行公式 vba 后用空白单元格替换“0”