我在使用YouTube API的代码中遇到了一个有趣的难题。我正在使用自定义播放暂停按钮来控制嵌入的YouTube视频。使用此HTML点击时,图标从播放切换为暂停:
<div class="media-play-btn-container" id="play-pause-toggle">
<div class="play-pause-ring"></div> //circle around play/pause icon
<a id="media-toggle" href=""><i class="icon ion-ios-play"></i></a>
</div>
和这个JS:
//toogle the play-pause button
$('#play-pause-toggle').click(function (e) {
e.preventDefault();
//the ion-pause is pulled from ionicons icons CDN
$(this).find('i').toggleClass('ion-ios-play').toggleClass('ion-pause');
});
此切换也应该控制youtube播放器的启动和停止。现在,如果我点击播放按钮它会启动视频,如果我点击暂停按钮,它会暂停视频(应该如此)。但是,如果我再次点击播放按钮,则没有任何反应!这是我写的YouTube API代码:
function onPlayerReady(event) {
//media-toggle is div ID for the play/pause icons
$('#media-toggle').click(function (event) {
player.playVideo();
});
//this is for custom progress bar, please disregard
time_total = convert_to_mins_and_secs(player.getDuration(), 1);
loopy();
}
function onPlayerStateChange(event) {
//this is code for custom progress bar
if (event.data == YT.PlayerState.ENDED) {
console.log("END!");
clearTimeout(timeout_setter);
document.getElementById("progress-bar-bottom").style.cssText = "transition: none;";
} else if (event.data == YT.PlayerState.PLAYING) {
console.log("PLAYING");
loopy();
document.getElementById("progress-bar-bottom").style.cssText = "transition: all 1s linear 0s;";
} else {
console.log(event.data);
}
// ==== HERE IS RELEVANT CODE ==== //
var state = player.getPlayerState();
if (state = 1) {
$('#media-toggle').click(function (event) {
player.pauseVideo();
});
} else {
$('#media-toggle').click(function (event) {
player.playVideo();
});
}
}
我该怎么做才能解决这个问题?感谢大家! :)