在JavaScript中暂停YouTube iFrame API [英] Pausing YouTube iFrame API in JavaScript
问题描述
我在幻灯片中嵌入了Youtube视频,当用户点击 img
缩略图时我想暂停:
I have a Youtube video embedded in a slideshow that I would like to pause when the user clicks on an img
thumbnail:
<li><iframe width="430" height="241" src="http://www.youtube.com/watch?v=XjUz8IT0CYg?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen id="my-video"></iframe></li>
我一直在使用Youtube API,但我很困惑如何开始使用。
I've been over the Youtube API but I'm confused how to get things started.
当我将?enablejsapi
追加到YouTube 视频的末尾时,API JS会自动加载吗? id
?
Does the API JS load automatically when I append ?enablejsapi
to the end of the YouTube video id
?
这是我的JS:
var player1 = document.getElementById('my-video');
$('img').click(function () {
player1.pauseVideo();
})
编辑:
这是我根据Matt的答案做的,对于任何想知道的人:
Here's what I did based on Matt's answer below, for anyone wondering:
<li><iframe width="430" height="241" src="http://www.youtube.com/embed/XjUz8IT0CYg?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen id="player-1"></iframe></li>
<li><iframe width="430" height="241" src="http://www.youtube.com/embed/HVhSasnVjMQ?enablejsapi=1&theme=light&showinfo=0" frameborder="0" allowfullscreen id="player-2"></iframe></li>
然后我的JS:
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Create YouTube player(s) after the API code downloads.
var player1;
var player2;
function onYouTubeIframeAPIReady() {
player1 = new YT.Player('player-1');
player2 = new YT.Player('player-2');
}
然后在 document.ready
:
$(document).ready(function () {
$(".slideshow-1 img").click(function () {
player1.stopVideo();
});
$(".slideshow-2 img").click(function () {
player2.stopVideo();
});
}
推荐答案
在嵌入字符串中追加?enablejsapi
并不会自动包含API代码。它只会注册API中的特定嵌入。
Appending ?enablejsapi
in the embed string does not automatically include the API code. It only registers that particular embed with the API.
您想在此处阅读第一个示例: https ://developers.google.com/youtube/iframe_api_reference
You want to read the first example here: https://developers.google.com/youtube/iframe_api_reference
- 异步代码段下载并执行YT iframe API
-
onYouTubeIframeAPIReady()
在API准备就绪时被触发 - 创建一个新的
YT.Pla是
对象 - 您的代码现在可以在您的播放器对象上调用
pauseVideo()
- The asynchronous code snippet downloads and executes the YT iframe API
onYouTubeIframeAPIReady()
is fired when the API is ready- Create a new
YT.Player
object - Your code can now call
pauseVideo()
on your player object
您很可能想要禁用img上的任何事件,直到 onYouTubeIframeAPIReady()
被触发。
You will most likely want to disable any events on your img until onYouTubeIframeAPIReady()
has been fired.
这篇关于在JavaScript中暂停YouTube iFrame API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!