javascript - 使用 JavaScript 或 jQuery 监听 Youtube 事件

标签 javascript jquery events youtube youtube-api

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

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

我正在尝试使四个视频中任何一个的 onStateChange 事件调用我称为 stopCycle() 的函数,该函数将在视频开始时停止 slider 玩。 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!');
}

最佳答案

YouTube Frame API 确实支持现有框架。为了提高使用率,我创建了一些辅助函数。看看下面的代码+注释和演示:http://jsfiddle.net/YzvXa/197

要将函数绑定(bind)到现有框架,您必须将 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);
})();

// 之前定义了核心函数。展望实现:

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);
}

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

player.mute();
  • 如果您只需调用简单的单向函数,则无需使用此代码。相反,请使用 this answer 中定义的函数 callPlayer
  • 如果您想同时多个帧实现此功能,请查看 this answer 还包括 getFrameIDYT_ready 的详细说明

关于javascript - 使用 JavaScript 或 jQuery 监听 Youtube 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7988476/

相关文章:

javascript - 为什么在 javascript 闭包中打印这个值?

javascript - 将 jQuery 添加到 wordpress 页面以显示时间/日期选择器

jquery - Accordion 旁边的边框没有更新

javascript - 选择要显示的随机图像

c# - new 运算符如何与 C# 中的委托(delegate)一起使用

php - 复选框 onclick 取消选中其他复选框

javascript - jQuery 函数 : why is the completion of the first event delayed until a second event finishes?

javascript - 选择所有不触发其各自 .change 功能的复选框

c# - 捕获控制台退出 C#

events - 处理 ViewModel 中的 TextBox 事件,例如 Text_changed