用 JavaScript 或 jQuery 监听 Youtube 事件 [英] Listening for Youtube Event in JavaScript or jQuery

查看:32
本文介绍了用 JavaScript 或 jQuery 监听 Youtube 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个滑块,其中包含 4 个通过 iframe 嵌入代码嵌入的 youtube 视频

I have a slider which includes 4 youtube videos that are embedded via the iframe embed code

http://www.youtube.com/embed/'.$i.'?enablejsapi=1

我试图让四个视频中的任何一个的 onStateChange 事件调用一个我调用的函数 stopCycle() 它将在视频开始时停止滑块玩.iframe 没有 ID.我不确定如何正确捕获此事件,并且可以使用任何关于我做错了什么的建议.

I'm trying to make the onStateChange event of any of the four videos call a function I have called stopCycle() which will stop the slider when the video begins to play. The iframes do not have an id. I'm not sure about how to capture this event properly and could use any advice as to what i'm doing wrong.

<script charset="utf-8" type="text/javascript" src="http://www.youtube.com/player_api"></script>

var playerObj = document.getElementById("tab2"); // the container for 1 of the 4 iframes

playerObj.addEventListener("onStateChange", "stopCycle");

function stopCycle(event) {
    alert('Stopped!');
}

推荐答案

YouTube Frame API是否支持现有框架.为了改进使用,我创建了一些辅助函数.看看下面的代码 + 评论和演示:http://jsfiddle.net/YzvXa/197

The YouTube Frame API does support existing frames. To improve the usage, I have created some helper functions. Have a look at the code + comments below and the demo: http://jsfiddle.net/YzvXa/197

要将函数绑定到现有框架,您必须将 ID 引用传递给框架.在您的情况下,框架包含在具有 id="tab2" 的容器中.我已经定义了一个更容易实现的自定义函数:

To bind functions to existent frames, you have to pass an ID reference to the frame. In your case, the frame is contained within a container with id="tab2". I have defined a custom function for an easier implementation:

function getFrameID(id){
    var elem = document.getElementById(id);
    if (elem) {
        if(/^iframe$/i.test(elem.tagName)) return id; //Frame, OK
        // else: Look for frame
        var elems = elem.getElementsByTagName("iframe");
        if (!elems.length) return null; //No iframe found, FAILURE
        for (var i=0; i<elems.length; i++) {
           if (/^https?://(?:www.)?youtube(?:-nocookie)?.com(/|$)/i.test(elems[i].src)) break;
        }
        elem = elems[i]; //The only, or the best iFrame
        if (elem.id) return elem.id; //Existing ID, return it
        // else: Create a new ID
        do { //Keep postfixing `-frame` until the ID is unique
            id += "-frame";
        } while (document.getElementById(id));
        elem.id = id;
        return id;
    }
    // If no element, return null.
    return null;
}

// Define YT_ready function.
var YT_ready = (function() {
    var onReady_funcs = [], api_isReady = false;
    /* @param func function     Function to execute on ready
     * @param func Boolean      If true, all qeued functions are executed
     * @param b_before Boolean  If true, the func will added to the first
                                 position in the queue*/
    return function(func, b_before) {
        if (func === true) {
            api_isReady = true;
            while (onReady_funcs.length) {
                // Removes the first func from the array, and execute func
                onReady_funcs.shift()();
            }
        } else if (typeof func == "function") {
            if (api_isReady) func();
            else onReady_funcs[b_before?"unshift":"push"](func); 
        }
    }
})();
// This function will be called when the API is fully loaded
function onYouTubePlayerAPIReady() {YT_ready(true)}

// Load YouTube Frame API
(function() { // Closure, to not leak to the scope
  var s = document.createElement("script");
  s.src = (location.protocol == 'https:' ? 'https' : 'http') + "://www.youtube.com/player_api";
  var before = document.getElementsByTagName("script")[0];
  before.parentNode.insertBefore(s, before);
})();

// 之前定义了核心功能.展望实施:

// Previously, core functions were defined. Look ahead for the implementation:

var player; //Define a player object, to enable later function calls, without
            // having to create a new class instance again.

// Add function to execute when the API is ready
YT_ready(function(){
    var frameID = getFrameID("tabs2");
    if (frameID) { //If the frame exists
        player = new YT.Player(frameID, {
            events: {
                "onStateChange": stopCycle
            }
        });
    }
});

// Example: function stopCycle, bound to onStateChange
function stopCycle(event) {
    alert("onStateChange has fired!
New state:" + event.data);
}

如果您想稍后调用其他函数,例如将视频静音,使用:

If you want to invoke additional functions at a later point, e.g. mute a video, use:

player.mute();

  • 如果您只需要调用简单的单向函数,则没有必要使用此代码.相反,请使用 这个答案.
  • 如果您想同时为多帧实现此功能,请查看这个答案.还包括对getFrameIDYT_ready的详细说明.
    • If you only have to call simple single-direction functions, it's not necessary to use this code. Instead, use the function callPlayer as defined at this answer.
    • If you want to implement this feature for multiple frames, simultaneously, have a look at this answer. Also includes a detailed explanation of getFrameID and YT_ready.
    • 这篇关于用 JavaScript 或 jQuery 监听 Youtube 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆