我想创建一个按钮,暂停自动播放的YouTube视频。
这是iframe:
<iframe id="music" width="0" height="0" src="https://www.youtube.com/embed/v_FucrYWy3k?rel=1&controls=0&showinfo=0&start=1&autoplay=1&enablejsapi=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
这是按钮:
<button onclick="mute()" type="button" name="button">mute</button>
而这个JS:
function mute(){
var myVideo = document.getElementById('music');
myVideo.pauseVideo();
}
我错过了什么?
看来,使用当前的Youtube API,您必须做的不仅仅是添加enablejsapi
作为嵌入的get参数。实际上,您必须包含here的API脚本,并使用自定义方法。你可以看看下面的代码或运行这个工作JSFiddle:
<iframe id="music" width="310" height="310" src="https://www.youtube.com/embed/v_FucrYWy3k?rel=1&controls=1&showinfo=0&start=1&autoplay=1&enablejsapi=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
<button id='button' type="button" name="button">mute</button>
和JS代码:
//create the script for the API and append it to the DOM
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('music', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
document.getElementById('button').addEventListener('click', function() {
player.pauseVideo();
})
}
这一切都在文档here中。
你最好使用youtube api。