how to get YouTube video id from image thumbnail source, and set as an iframe?

前端 未结 3 430
情歌与酒
情歌与酒 2020-12-22 08:58

So if the image tag is


I don\'t know how to e

相关标签:
3条回答
  • 2020-12-22 09:12

    I think you can do this more easily if you'll start to study the YouTube API.

    0 讨论(0)
  • 2020-12-22 09:17

    Make the URL as an array and than take the second to last part. For example this also works with CSS background-image.

    id = $('div').attr('style').split('/');
    id = id[id.length-2];
    alert("YouTube ID: " + id);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div style="background-image:url('https://img.youtube.com/vi/MHUOty8-Ty0/0.jpg');"></div>

    https://jsfiddle.net/Wobbo/wfyL1hem/7/

    0 讨论(0)
  • 2020-12-22 09:36

    This extracts the YouTube ID using a Regular Expression, I made the assumption that it would be a minimum of eleven characters as the first YouTube Video ID has 11.

    <img src="http://i1.ytimg.com/vi/LL0Y4MZ45bo/0.jpg" class="youtubeimg"></img>
    <iframe src="" class="youtubeiframe"></iframe>
    
    <script>
        $(function (){
            var youtubeid = $(".youtubeimg").attr("src").match(/[\w\-]{11,}/)[0];
            $(".youtubeiframe").attr({ 
                  src: "http://www.youtube.com/embed/" + youtubeid,
            });
        });
    </script>
    

    This works, however the YouTube Player API may provide you with a more stable solution to loading that iFrame, in the future once it becomes stable I would recommend the YouTube iFrame API

    0 讨论(0)
提交回复
热议问题