在JavaScript或jQuery中收听Youtube事件

Dav*_*iss 19 javascript youtube jquery events youtube-api

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

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

我试图让onStateChange四个视频中的任何一个事件调用我调用的函数stopCycle(),当视频开始播放时,它将停止滑块.iframe没有id.我不确定如何正确地捕捉这个事件,并且可以使用任何关于我做错的建议.

<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!');
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*b W 42

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

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

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);
})();
Run Code Online (Sandbox Code Playgroud)

//以前,核心功能已定义.展望实施:

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!\nNew state:" + event.data);
}
Run Code Online (Sandbox Code Playgroud)

如果您想稍后调用其他功能,例如将视频静音,请使用:

player.mute();
Run Code Online (Sandbox Code Playgroud)
  • 如果您只需调用简单的单向函数,则无需使用此代码.而是使用此答案中callPlayer定义的函数.
  • 如果要为多个帧实现此功能,请同时查看此答案.还包括的详细说明getFrameIDYT_ready.