javascript将YouTube链接转换为嵌入视频

时间:2016-04-01 18:52:35

标签: javascript jquery html youtube

我在我的页面上有许多链接所有在随机位置记下来。如果有这样的链接:

<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>');
    });
});

2 个答案:

答案 0 :(得分:0)

我会查看此链接。它是关于Youtube iFrame的Google文档。 https://developers.google.com/youtube/player_parameters#Embedding_a_Player

答案 1 :(得分:0)

您只需点击href标记即可提取anchor值,并将现有anchor标记替换为iframe标记。

<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>
<br>
<a href="http://www.youtube.com/embed/XGSy3_Czz8k" title="Go To http://www.youtube.com/embed/XGSy3_Czz8k" target="_blank" style="text-decoration:none;">http://www.youtube.com/embed/XGSy3_Czz8k</a>
<script>
$('a').click(function(e)
{
   var target = $(this).attr('href');
   var iframe = $('<iframe/>',{ width: "420", height: "315" , src : target});
   $(this).replaceWith(iframe);
   e.preventDefault();
});
</script>

示例:https://jsfiddle.net/4nqhqu03/