在JavaScript中暂停YouTube iFrame API

我在幻灯片中嵌入了Youtubevideo,当用户点击img缩略图时我想暂停:

 
  • 我一直在Youtube API上,但我很困惑如何开始。

    当我将?enablejsapi追加到YouTube video id的末尾时,API JS会自动加载吗?

    这是我的JS:

     var player1 = document.getElementById('my-video'); $('img').click(function () { player1.pauseVideo(); }) 

    编辑:

    以下是我根据马特的答案做的事情,对于任何想知道的人:

     
  • 然后是我的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(); }); } 

    在embed字符串中附加?enablejsapi不会自动包含API代码。 它只注册API的特定嵌入。

    您想在此处阅读第一个示例: https : //developers.google.com/youtube/iframe_api_reference

    1. 异步代码段下载并执行YT iframe API
    2. API准备就绪时会触发onYouTubeIframeAPIReady()
    3. 创建一个新的YT.Player对象
    4. 您的代码现在可以在您的播放器对象上调用pauseVideo()

    onYouTubeIframeAPIReady()被触发之前,您很可能希望禁用img上的任何事件。

    如果你想让你的JS在外部文件中使用:

    HTML

       

    JS

     var yt_int, yt_players={}, initYT = function() { $(".ytplayer").each(function() { yt_players[this.id] = new YT.Player(this.id); }); }; $.getScript("//www.youtube.com/player_api", function() { yt_int = setInterval(function(){ if(typeof YT === "object"){ initYT(); clearInterval(yt_int); } },500); }); 

    控制video

     yt_players['player_id'].playVideo(); 

    我这样做的原因是因为我通过CMS动态加载video,并以叠加方式打开。 我设置了关闭/打开覆盖function来播放/暂停video。

    我有另一个解决方案:

       

     $('.ytplayer').each(function(){ //this.contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*'); this.contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*') }); 

    Youtube iframe API中的所有自定义控件列表。 在Github上查看

    • 暂停
    • 停止
    • 声音关闭
    • 声音开
    • 重新开始