【问题标题】:javascript turn a YouTube link into embed videojavascript 将 YouTube 链接转换为嵌入视频
【发布时间】:2016-04-01 18:52:35
【问题描述】:

我的页面上有很多链接,都是在随机的地方写的。如果有这样的链接:

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

【问题讨论】:

  • 是的,这可以使用 JavaScript 完成..
  • 您实际尝试过什么?请向我们展示您的 JavaScript 代码以及您希望它做什么。
  • StackOverflow 不是代码编写服务 - 您必须先尝试一些东西,我们才能为您提供帮助。
  • @MathiasBecher 我已经非常努力地尝试了一些 JavaScript,但效果不佳;你能帮我修一下吗???

标签: javascript jquery html youtube


【解决方案1】:

我会检查这个链接。这是 Google 在 Youtube iFrame 上的文档。 https://developers.google.com/youtube/player_parameters#Embedding_a_Player

【讨论】:

    【解决方案2】:

    您只需点击anchor 标记即可提取href 值,并将现有的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/

    【讨论】:

    • 效果不好
    • 你能查看我上面的 Javascript 代码吗
    猜你喜欢
    • 2013-07-11
    • 1970-01-01
    • 2011-06-09
    • 2014-03-03
    • 2015-09-29
    • 2014-07-07
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多