2014/03/21

jQuery Video Creator Plugin

這個 plugin 可以初始擁有 YouTube 或 Vimeo 的超連結點選之後將自己或指定的目標轉換成影片。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Video</title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="js/jquery.video_creator.js"></script>
    <script>
    $(function() {
        $('a').video_creator({
            width: 200,
            height: 100,
            target: '#video'
        });
    });
    </script>
</head>
<body>
<a href="https://www.youtube.com/watch?v=p6oaqY6flJg">Youtube</a>
<a href="http://vimeo.com/89495751">Vimeo</a>
<div id="video"></div>
</body>
</html>
(function() {
    $.fn.video_creator = function(options) {
        var params = {
            width: 640,
            height: 360,
            target: ''
        }

        var set = $.fn.extend(params, options);

        return this.each(function() {
            var url = $(this).prop('href'),
                id = '',
                matches = '',
                result = '';

            // Youtube
            if (-1 !== url.toLowerCase().indexOf('youtube')) {
                matches = url.match(/[\\?\\&]v=([^\\?\\&]+)/);
                id = matches[1];
                result = '<iframe width="' + set.width + '" height="' + set.height + '" src="//www.youtube.com/embed/' + id + '" frameborder="0" allowfullscreen></iframe>';
            }

            // Vimeo
            if (-1 !== url.toLowerCase().indexOf('vimeo')) {
                matches = url.match(/\/\/(www\.)?vimeo.com\/(\d+)($|\/)/);
                id = matches[2];
                result = '<iframe src="http://player.vimeo.com/video/' + id + '?title=0&amp;byline=0&amp;portrait=0&amp;badge=0&amp;color=ffffff" width="' + set.width + '" height="' + set.height + '" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
            }

            $(this).on('click', function() {
                if ('' === set.target) {
                    $(this).replaceWith(result);
                } else {
                    $(set.target).html(result);
                }

                return false;
            });
        });
    }
}(jQuery));

沒有留言: