示例代码:
<div id="ytplayer"></div>
<a id="start" href="#">start</a>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'U6oKcAXiVlo',
playerVars: { 'autoplay': 0, 'controls': 0, 'showinfo': 0 },
});
}
document.getElementById("start").addEventListener("click", function () {
player.playVideo();
});
</script>
可重现的测试用例: http: //fiddle.jshell.net/3fpusLm5/show/
player 变量在范围内。但是对对象上应该可用的方法(例如 playVideo、pauseVideo)的调用不起作用。它说Object does not support this property or method
。
该代码适用于大多数现代浏览器。我确定播放器已经加载。我已经测试了 onReady 回调,还尝试等待 30 秒。