gpt4 book ai didi

javascript - 有时YouTube API尚未准备就绪

转载 作者:行者123 更新时间:2023-12-03 06:15:06 26 4
gpt4 key购买 nike

我正在尝试使用其API包含youtube vid。但是,有时(确实是随机的。多数情况下,它是可行的)单击播放按钮时出现错误:

Cannot read property 'playVideo' of undefined

这就是我包含API的方式:

var player;

function onYouTubeIframeAPIReady() {
player = new YT.Player('video-intro', {
width: 100,
height: 100,
videoId: '<id>',
playerVars: {
color: 'white',
controls: 0,
showinfo: 0
}
});
}

$(document).ready(function() {
$('#play-intro').click(function() {
player.playVideo();
$('#video-intro').addClass('showvid');
});
});
#video-intro {
display: none;
&.showvid {
display: block;
}
}
<head>
<script src="https://www.youtube.com/iframe_api"></script>
</head>

<body>
<div id="video-intro"></div>
<a id="play-intro">Play</a>
</body>

最佳答案

您需要 call 事件以启动播放器。而且,您无法在视频加载之前播放视频。这就是为什么您会收到未定义的错误。我已经添加了事件和功能检查。可以在这里找到更好的示例enter link description here

var player;

function onYouTubeIframeAPIReady() {
player = new YT.Player('video-intro', {
width: 100,
height: 100,
videoId: 'TZbUi0FP5AM', //T7Kmc7T-pjY (old, short)
playerVars: {
color: 'white',
controls: 0,
showinfo: 0
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});

}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}



$(document).ready(function() {
$('#play-intro').click(function() {
onYouTubeIframeAPIReady();

$('#video-intro').addClass('showvid');
});
});
#video-intro {
display: none;
&.showvid {
display: block;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<script src="https://www.youtube.com/iframe_api"></script>
</head>

<body>
<div id="video-intro"></div>
<a id="play-intro">Play</a>
</body>

关于javascript - 有时YouTube API尚未准备就绪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44884461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com