我的网站由于嵌入了太多视频而加载缓慢。我看过一个解决方法,就是在视频嵌入位置上方放置一张图片,当你点击它时,视频就会被加载。请问有谁能帮助我解决这个问题?也许当你将鼠标悬停在图片上时,Youtube 视频会自动加载?非常感谢!
我的网站由于嵌入了太多视频而加载缓慢。我看过一个解决方法,就是在视频嵌入位置上方放置一张图片,当你点击它时,视频就会被加载。请问有谁能帮助我解决这个问题?也许当你将鼠标悬停在图片上时,Youtube 视频会自动加载?非常感谢!
当用户单击图片后,只需使用jQuery插入嵌入代码:
简单示例代码:HTML
<div id="video" style="background-color:red; width:560px; height:315px;"></div>
jQuery:
$('#video').on('click', function() {
$(this).html('<iframe width="560" height="315" src="//www.youtube.com/embed/9bZkp7q19f0?autoplay=1" frameborder="0" allowfullscreen></iframe>').css('background', 'none');
});
如果您想让视频自动播放,请像我一样在URL末尾添加?autoplay=1
。<div id="video" style="background-color:red; width:560px; height:315px;">
<a href="http://www.youtube.com/watch?v=9bZkp7q19f0" class="youtube"></a></div>
jQuery:
$('#video').on('click', function() {
$(this).html('<iframe width="560" height="315" src="//www.youtube.com/embed/9bZkp7q19f0?autoplay=1" frameborder="0" allowfullscreen></iframe>').css('background', 'none');
});
function getYoutubeID(url) {
var id = url.match("[\\?&]v=([^&#]*)");
id = id[1];
return id;
};
$('a.youtube').each(function() {
var id = getYoutubeID( this.href );
this.id = id;
var thumb_url = "http://img.youtube.com/vi/"+id+"/maxresdefault.jpg";
$('<img width="100%" src="'+thumb_url+'" />').appendTo($('#video'));
});
带有缩略图的代码: http://jsfiddle.net/89uVe/4/
autoplay
在 iDevices 上不起作用。 - putvande