问题
I already have a plugin that embeds videos on my site called oembed. What I need is a javascript code that converts youtube iframes or another embeds to the default image of the videos, when the image is clicked video player appears and plays. Google + and facebook have implemented this idea. Please let me know how to make this happen.
This is an example of my youtube iframe:
<iframe width="267" height="200" src="http://www.youtube.com/embed/YOUTUBEID;feature=oembed" frameborder="0" allowfullscreen=""></iframe>
I found two codes and modified them into this:
var RE = /embed\/([a-zA-Z0-9_-]{11})/;
jQuery( "iframe" ).each(function(){
var id = ( this.src.match( RE ) || [] )[1];
if( id ) {
jQuery( this ).replaceWith(
'<img width="420" height="215" src="http://i1.ytimg.com/vi/'+id+'/hqdefault.jpg"'+
' class="youtube" />' );
}
});
var youtubeIFRAME = '<p class="close">CLOSE</span><iframe data-address="$1" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>';
jQuery("img.youtube").click(function(){
var $this = $(this);
$this.replaceWith('<iframe width="420" height="315" src="http://www.youtube.com/embed/$1?rel=0" frameborder="0" allowfullscreen></iframe>'
.replace("$1", $this.attr("data-address")));
});
The problem is now the embed works but there is a problem catching the video Id.
回答1:
The problem is that there's a link element surrounding your iframe. I believe you can fix that by removing the link and using something else, like a div:
function changeiframe() {
objs = document.getElementsByTagName('iframe');
for (i in objs) {
if (objs[i].src) {
vidid = objs[i].src.split('/')[4].split('?')[0];
linkurl = 'http://www.youtube.com/watch?v='+vidid;
bgurl = 'http://img.youtube.com/vi/'+vidid+'/0.jpg';
imgurl = 'playsh.png';
container = document.createElement('div');
container.style.backgroundImage = 'url('+bgurl+')';
container.className += "youvid";
img = document.createElement('img');
img.src = imgurl;
container.appendChild(img);
objs[i].outerHTML = container.outerHTML;
}
}
}
来源:https://stackoverflow.com/questions/8902718/google-and-facebook-style-iframe-youtube-video-by-default-shows-video-image