试图做一些类似于 facebook 的东西。我已经创建了这个 javascript url 模式转换器。当用户点击论坛帖子的提交按钮时,可能会触发类似的事情 - 将 url 转换为嵌入的 html 变体。有什么改进方法吗?
http://jsfiddle.net/88Ms2/377/
var videoEmbed = {
invoke: function(){
$('body').html(function(i, html) {
return videoEmbed.convertVideo(html);
});
},
convertVideo: function(html){
var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;
var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g;
if(pattern1.test(html)){
console.log("html", html);
var replacement = '<iframe width="420" height="345" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
var html = html.replace(pattern1, replacement);
}
if(pattern2.test(html)){
console.log("html", html);
var replacement = '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
var html = html.replace(pattern2, replacement);
}
return html;
}
}
setTimeout(function(){
videoEmbed.invoke();
},3000);
最佳答案
最新代码 ******** http://jsfiddle.net/88Ms2/378/
这模仿了 facebook 的帖子功能 - 将 youtube、vimeo 或图像转换为基于媒体的链接。这将有助于承担
有兴趣增强代码。
var videoEmbed = {
invoke: function(){
$('body').html(function(i, html) {
return videoEmbed.convertMedia(html);
});
},
convertMedia: function(html){
var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;
var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g;
var pattern3 = /([-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
if(pattern1.test(html)){
var replacement = '<iframe width="420" height="345" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';
var html = html.replace(pattern1, replacement);
}
if(pattern2.test(html)){
var replacement = '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
var html = html.replace(pattern2, replacement);
}
if(pattern3.test(html)){
var replacement = '<a href="$1" target="_blank"><img class="sml" src="$1" /></a><br />';
var html = html.replace(pattern3, replacement);
}
return html;
}
}
关于Javascript - 将 youtube/vimeo url 转换为嵌入版本以用于论坛评论功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22544625/