我的页面上有很多链接,全都随意地写在各处。如果有这样的链接:
<a href="https://youtu.be/4tG274QuqHM" title="Go To https://youtu.be/4tG274QuqHM" target="_blank" style="text-decoration:none;">https://youtu.be/4tG274QuqHM</a>
或
<a href="https://youtube.com/watch?v=4tG274QuqHM" title="Go To https://youtube.com/watch?v=4tG274QuqHM" target="_blank" style="text-decoration:none;">https://youtube.com/watch?v=4tG274QuqHM</a>
或
Any Other YouTube Video Link Format
JavaScript 中是否有任何方法可以获取任何形式的 YouTube 链接并将其转换为 YouTube 嵌入 Iframe,通过使用 JavaScript 使其最终看起来像这样;
<iframe width="420" height="345" src="http://www.youtube.com/embed/4tG274QuqHM?autoplay=0&autohide=1&controls=2&rel=0" frameborder="0" allowfullscreen="true"></iframe>
任何人都可以修复此代码以使其正常工作吗???
$(document).ready(function() {
$('a').each(function() {
var matches = $(this).attr("href").match(/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/);
if(matches){
$(this).attr("class","youtube-link");
}
});
$('a.youtube-link').each(function() {
var yt_url = this.href,
yt_id = yt_url.split('?v=')[1],
yt_id = yt_url.split('embed/')[1],
yt_title = $(this).text();
$(this).replaceWith('<iframe style="max-width:560px;max-height:315px;" width="600" height="600" src="http://www.youtube.com/embed/' + yt_id + '?rel=0" frameborder="0" allowfullscreen></iframe>');
});
});
最佳答案
我会检查这个链接。这是 Google 关于 Youtube iFrame 的文档。 https://developers.google.com/youtube/player_parameters#Embedding_a_Player
关于javascript 将 YouTube 链接转换为嵌入视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36363791/