Javascript YouTube API 目标(多个)现有 iframe

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8948403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:11:39  来源:igfitidea点击:

YouTube API Target (multiple) existing iframe(s)

javascriptyoutube-apiyoutube-javascript-api

提问by SparrwHawk

I'm trying to understand how to target an existing iframe using the YouTube API (i.e. without constructing an iframe with the script).

我试图了解如何使用 YouTube API 定位现有的 iframe(即不使用脚本构建 iframe)。

As usual, Google does not give enough API examples, but explains that it IS possible, here http://code.google.com/apis/youtube/iframe_api_reference.html

像往常一样,谷歌没有提供足够的 API 示例,但解释说这是可能的,这里http://code.google.com/apis/youtube/iframe_api_reference.html

Here is an example of what I'm trying to do - the video underneath the thumbnail should play. I am almost there, but only the first video plays...

这是我正在尝试做的一个示例 - 缩略图下方的视频应该播放。我快到了,但只播放第一个视频...

http://jsfiddle.net/SparrwHawk/KtbYR/2/

http://jsfiddle.net/SparrwHawk/KtbYR/2/

回答by Rob W

TL;DR: DEMO: http://jsfiddle.net/KtbYR/5/

TL;DR:演示:http: //jsfiddle.net/KtbYR/5/

YT_ready, getFrameIDand onYouTubePlayerAPIReadyare functions as defined in this answer. Both methods can be implemented without any preloaded library. In my previous answer, I showed a method to implement the feature for a single frame.

YT_ready,getFrameIDonYouTubePlayerAPIReady本答案中定义的函数。这两种方法都可以在没有任何预加载库的情况下实现。在我之前的回答中,我展示了一种为单帧实现该功能的方法。

In this answer, I focus on multiple frames.

在这个答案中,我专注于多个框架。

HTML example code(important tags and attributes are capitalized, <iframe src id>):

HTML 示例代码(重要标签和属性大写,<iframe src id>):

<div>
  <img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'>
  <IFRAME ID="frame1" SRC="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1" width="640" height="390" frameborder="0"></IFRAME>
</div>
<div>
  <img class='thumb' src='http://i2.cdnds.net/11/34/odd_alan_partridge_bio_cover.jpg'>
  <IFRAME ID="frame2" SRC="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1" width="640" height="390" frameborder="0"></IFRAME>
</div>

JavaScript code (YT_ready, getFrameID, onYouTubePlayerAPIReadyand the YouTube Frame APIscript loader are defined here)

JavaScript代码(YT_readygetFrameIDonYouTubePlayerAPIReadyYouTube的API框架加载器中定义的脚本在这里

var players = {}; //Define a player storage object, to expose methods,
                  //  without having to create a new class instance again.
YT_ready(function() {
    $(".thumb + iframe[id]").each(function() {
        var identifier = this.id;
        var frameID = getFrameID(identifier);
        if (frameID) { //If the frame exists
            players[frameID] = new YT.Player(frameID, {
                events: {
                    "onReady": createYTEvent(frameID, identifier)
                }
            });
        }
    });
});

// Returns a function to enable multiple events
function createYTEvent(frameID, identifier) {
    return function (event) {
        var player = players[frameID]; // Set player reference
        var the_div = $('#'+identifier).parent();
        the_div.children('.thumb').click(function() {
            var $this = $(this);
            $this.fadeOut().next().addClass('play');
            if ($this.next().hasClass('play')) {
                player.playVideo();
            }
        });
    }
}

In my previous answer, I bound the onStateChangeevent. In this example, I used the onReadyevent, because you want to call the functions only once, at initialization.

在我之前的回答中,我绑定了onStateChange事件。在此示例中,我使用了onReady事件,因为您只想在初始化时调用函数一次。

This example works as follows:

此示例的工作方式如下:

  • The following methods are defined in this answer.

    1. The YouTube Frame APIis loaded from http://youtube.com/player_api.
    2. When this external script has finished loading, onYoutubePlayerAPIReadyis called, which in his turn activates all functions as defined using YT_ready
  • The declaration of the following methods are shown here, but implemented using this answer. Explanation based on the example:

    1. Loops through each <iframe id>object, which is placed right after <.. class="thumb">.
    2. At each frame element, the idis retrieved, and stored in the identifiervariable.
    3. The internal ID of the iframe is retrieved through getFrameID. This ensures that the <iframe>is properly formatted for the API. In this example code, the returned ID is equal to identifier, because I have already attached an ID to the <iframe>.
    4. When the <iframe>exists, and a valid YouTube video, a new player instance is created, and the reference is stored in the playersobject, accessible by key frameID.
    5. At the creation of the player instance, a **onReady* event is defined. This method will be invoked when the API is fully initialized for the frame.
    6. createYTEvent
      This method returns a dynamically created function, which adds functionality for separate players. The most relevant parts of the code are:

      function createYTEvent(frameID, identifier) {
          return function (event) {
              var player = players[frameID]; // Set player reference
              ...
                      player.playVideo();
          }
      }
      
      • frameIDis the ID of the frame, used to enable the YouTube Frame API.
      • identifieris the ID as defined in YT_ready, not necessarily an <iframe>element. getFrameIDwill attempt to find the closest matching frame for a given id. That is, it returns the ID of a given <iframe>element, or: If the given element is not an <iframe>, the function looks for a child which is a <iframe>, and returns the ID of this frame. If the frame does not exists, the function will postfix the given ID by -frame.
      • players[playerID]` refers to the initialized player instance.
  • 此答案中定义了以下方法。

    1. YouTube的框架API从加载http://youtube.com/player_api
    2. 当这个外部脚本完成加载时,onYoutubePlayerAPIReady被调用,它依次激活使用定义的所有函数YT_ready
  • 此处显示了以下方法的声明,但使用此答案实现。基于示例的说明:

    1. 循环遍历每个<iframe id>放置在 之后的对象<.. class="thumb">
    2. 在每个框架元素处,id检索 并存储在identifier变量中。
    3. iframe 的内部 ID 通过 检索getFrameID。这可确保<iframe>为 API 正确格式化。在此示例代码中,返回的 ID 等于identifier,因为我已经将 ID 附加到<iframe>.
    4. <iframe>存在且有效的 YouTube 视频时,将创建一个新的播放器实例,并将引用存储在players对象中,可通过 key 访问frameID
    5. 在创建播放器实例时,onReady定义了 ** * 事件。当 API 为框架完全初始化时,将调用此方法。
    6. createYTEvent
      此方法返回一个动态创建的函数,它为单独的播放器添加功能。代码中最相关的部分是:

      function createYTEvent(frameID, identifier) {
          return function (event) {
              var player = players[frameID]; // Set player reference
              ...
                      player.playVideo();
          }
      }
      
      • frameID是框架的 ID,用于启用YouTube 框架 API
      • identifier是 中定义的 ID YT_ready,不一定是<iframe>元素。getFrameID将尝试为给定的 id 找到最接近的匹配帧。也就是说,它返回给定<iframe>元素的 ID ,或者: 如果给定元素不是 an <iframe>,则该函数查找是 a 的子元素<iframe>,并返回此框架的 ID。如果框架不存在,该函数会将给定的 ID 后缀-frame.
      • player[playerID]` 指的是初始化的播放器实例。

Make sure that you alsocheck this answer, because the core functionality of this answer is based on that.

确保您检查了此答案,因为此答案的核心功能基于此。

Other YouTube Frame API answers. In these answers, I showed various implementations of the YouTube Frame/JavaScript API.

其他 YouTube 框架 API 答案。在这些答案中,我展示了 YouTube Frame/JavaScript API 的各种实现。