我想在我的页面上的任何play anchor <a> tag
上播放我的视频,
如果它处于暂停状态,那么它必须开始播放。如果它处于播放状态,则点击播放后必须开始播放。
<script type="text/javascript" src="http://www.youtube.com/player_api"> </script>
<script>
var player;
function onYouTubePlayerAPIReady() {player = new YT.Player('player');}
</script>
<iframe id="player" style="position: relative; height: 220px; width: 400px" src="https://www.youtube.com/embed/YL_OcLayJPg?rel=0&enablejsapi=1"></iframe><br>
<a href="javascript: void(0)" onclick="player.playVideo(); return false">play</a><br>
<a href="javascript: void(0)" onclick="player.pauseVideo(); return false">pause</a>
它在localhost上的HTML页面中工作,但在PHP文件中的服务器上不起作用。
它无法在服务器上运行。
答案 0 :(得分:1)
必须在play/pause
初始化中的'onReady'
事件处理程序中附加
YT.Player
个事件。
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady
}
});
}
function onPlayerReady() {
// bind events
var playButton = document.getElementById("play");
playButton.addEventListener("click", function() {
player.playVideo();
});
var pauseButton = document.getElementById("pause");
pauseButton.addEventListener("click", function() {
player.pauseVideo();
});
}
<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
<iframe id="player" style="position: relative; height: 220px; width: 400px" src="https://www.youtube.com/embed/YL_OcLayJPg?rel=0&enablejsapi=1"></iframe>
<br>
<a href="javascript: void(0)" id='play'>play</a>
<br>
<a href="javascript: void(0)" id='pause'>pause</a>
注意:您可以在<script>
中链接到它,但所有文档都显示加载async style
,这对第三方脚本来说总是有用。< / p>
// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);