我有一个示例视频,它是用户将视频从 youtube 拖到轻量级 CMS 的页面 block 中的结果。视频在界面结果中显示正常,但即使从 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>
最佳答案
这样您就可以自动播放来自 YouTube 的视频
<!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>
关于javascript - 通过简单的JS强制iframe自动播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55937651/