我在我的网络应用程序中使用了youtube API,因为我懒得加载视频iframe,我还没有使用<iframe>
dom对象。相反,我已将youtube视频ID提供给<div>
标记,然后在其上添加了静态图片。
当用户点击图像时,视频对象将被加载并播放。
我遇到的问题是白色背景,在视频对象完成加载之前显示片刻。
我只对IE有这个问题。
使用Javascript:
tag = document.createElement('script'), tag.src = '//www.youtube.com/iframe_api';
var a = document.getElementsByTagName('script')[0];
a.parentNode.insertBefore(tag, a);
var playerID = 0;
function onYouTubeIframeAPIReady() {
rhsID = $('.video_wrap > div > div > div > div').attr('id'), $('.ytPlyr_1').each(function() {
$(this).css({
'background-image': 'url(https://i.ytimg.com/vi/' + this.id + '/mqdefault.jpg)',
filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=https://i.ytimg.com/vi/' + this.id + "/sddefault.jpg',sizingMethod='scale')",
'-ms-filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=https://i.ytimg.com/vi/' + this.id + "/sddefault.jpg',sizingMethod='scale')"
}), $(this).append($('<div/>', {
'class': 'playBtn'
}));
}), $('.playBtn').click(function() {
var playedVid = $(this).parent().attr('id');
loadYTPlayer(playedVid);
}), $('.videos ul').hasClass('video-list') == 1 && $('.video-list').animate({
height: parseInt(toggleVideoThumList(MAXTOSHOW))
});
}
function loadYTPlayer(a) {
loadVideo(1, a), getVideoData($(this));
}
function loadVideo(a, b) {
if (null == b) {
var c = $.trim($('.ytPlyr_' + a).prop('id'));
addedMultiID[a - 1] = c;
} else var c = b;
player[playerID] = new YT.Player(c, {
height: '100%',
width: '100%',
videoId: c,
playerVars: {
rel: 0,
autoplay: 1,
wmode: "opaque"
},
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
}), $('.ytPlyr_' + a).addClass('loaded'), playerID++;
}
function getVideoData(a) {
var b = $.trim($(a).prop('id')),
c = $(a).prop('src');
$.ajax({
type: 'POST',
url: '/getYouTubeVideoData',
dataType: 'json',
data: {
videoId: b
}
}).done(function(a) {
jQuery.each(a.items, function(a, d) {
time = d.contentDetails.duration.replace(/\d+/g, function(a) {
return '0'.substr(a.length - 1) + a;
}).replace(/[H|M]/g, ':').replace(/[PT|S]/g, ''), time = 2 == time.length ? '00:' + time : time, thumbnail = d.snippet.thumbnails.medium.url, $($($($('#' + b).parent())).find('div.video-desc span.video-time')[0]).text(time), jQuery.each($($('#' + b).parent()).find('meta'), function(a, b) {
itemprop = $(b).attr('itemprop'), 'duration' == itemprop ? $(b).prop('content', d.contentDetails.duration) : 'thumbnailUrl' == itemprop ? $(b).prop('content', thumbnail) : 'embedUrl' == itemprop ? $(b).prop('content', c) : 'uploadDate' == itemprop && $(b).prop('content', d.snippet.publishedAt);
});
});
});
}
function onPlayerReady(a) {
for (var j = 0; j < player.length; j++) player[j].getIframe().id != a.target.getVideoData().video_id && player[j].getPlayerState() == 1 && player[j].pauseVideo();
}
function onPlayerStateChange(a) {
console.log("state changed");
}
HTML:
<div id="5dR3Enz5F3s" class="ytPlyr_1 ytplayer"></div>