从URL嵌入Youtube视频 [英] Embed Youtube video from URL

查看:294
本文介绍了从URL嵌入Youtube视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



所以这件事情是这样的,我们已经在一个项目中工作,但我需要一点帮助:用户可以在文本框中输入youtube网址,并自动生成嵌入式iframe视频,以便他可以预览而无需重新加载页面



我该怎么办?那么?

a找到了两个分离的脚本,可以帮助我,但我不能让它们在同一时间工作:



从URL中提取YouTube视频ID:

  [http://codepen.io/catmull/pen/cnpsK] [1] 

使用JavaScript优化的YouTube Embed:

  [http://codepen.io/SitePoint/pen/CKFuh] [1] 

有什么想法?
如果你用一个实际的例子来回答,那真的会有帮助:)

https://www.youtube.com/watch?v=sGbxmsDFVnE ,
您可以通过将视频id截断并放在youtube.com/embed/



的末尾来嵌入,您可以使用string.split()获取视频ID。

  var url =https://www.youtube.com/watch?v=sGbxmsDFVnE; 
var id = url.split(?v =)[1]; // sGbxmsDFVnE

var embedlink =http://www.youtube.com/embed/+ id; //www.youtube.com/embed/sGbxmsDFVnE

然后只需将该嵌入链接源设为页面上现有的iframe

  document.getElementById(myIframe)。src = embedLink; 

iframe的示例

 < iframe id =myIframewidth =560height =315frameborder =0allowfullscreen>< / iframe> 

工作代码

Im new in all this amazing thing called front end and i´m already working in a project but i need a little help with this:

So the thing is that the user could enter a youtube URL in a text box and a embed iframe video is automatically generated from it so he can preview it without reloading the page

How could i do that?

a have found 2 separated scripts that could help but i can´t make them work at the same time:

Extract YouTube video ID from URL:

[http://codepen.io/catmull/pen/cnpsK][1]

YouTube Embed Optimized with JavaScript:

[http://codepen.io/SitePoint/pen/CKFuh][1]

Any ideas? It will really help me if you answer with a live example :)

解决方案

if you have youtube url https://www.youtube.com/watch?v=sGbxmsDFVnE, you can embed it by taking the video id off the end and putting at the end of youtube.com/embed/

you can get the video id using string.split()

var url = "https://www.youtube.com/watch?v=sGbxmsDFVnE";
var id = url.split("?v=")[1]; //sGbxmsDFVnE

var embedlink = "http://www.youtube.com/embed/" + id; //www.youtube.com/embed/sGbxmsDFVnE

then just make that embed link the source to an existing iframe on the page

document.getElementById("myIframe").src = embedLink;

example of an iframe

<iframe id="myIframe" width="560" height="315" frameborder="0" allowfullscreen></iframe>

working code here

这篇关于从URL嵌入Youtube视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆