The YouTube 框架 API does支持现有框架。为了提高使用率,我创建了一些辅助函数。看看下面的代码+注释和演示:http://jsfiddle.net/YzvXa/197
要将函数绑定到现有框架,您have to将 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();
- 如果您只需致电简单单向函数,没有必要使用此代码。相反,使用该函数
callPlayer
定义为这个答案.
- 如果你想实现这个功能多帧,同时看看这个答案. 还包括详细的解释
getFrameID
and YT_ready
.