読者です 読者をやめる 読者になる 読者になる

Devlion Memo

どことなくそれっぽい大学生の日記

指定の要素にYoutubeをはっつける

こんな感じ.

https://jsfiddle.net/0b7dtvqc

Youtube Iframe APIとかいうの使った.

jquery.youtube.js

(function($) {
    $.fn.youtubePlayer = function(options) {

        function loadPlayer(element, settings, callback) {
            $.getScript("//www.youtube.com/iframe_api");
            // スコープ注意
            window.onYouTubeIframeAPIReady = function () {
                var options = {
                    videoId: settings.videoId,
                    playerVars: {
                        rel: 0,
                        controls: 0,
                        showinfo: 0,
                        showsearch: 0,
                        hd: settings.hd ? 1 : 0,
                        wmode: "transparent",
                        loop: settings.loop ? 1 : 0,
                        playlist: ""
                    },
                    events: {
                        onReady: function (e) {
                            player.mute();
                            player.playVideo();
                        },
                        onStateChange: function (e) {
                            if (e.data == 2 || e.data == 0) {
                                player.playVideo();
                            }
                        }
                    }
                };

                player = new YT.Player(element.attr("id"), options);

                callback(player);
            };
        }

        function resizePlayer(element, ratio) {
            element.css({
                width: $(window).width(),
                height: $(window).width() * (1 / ratio)
            });
        }

        var defaults = {
            videoId: "",
            loop: true,
            hd: false,
            ratio: 16/9
        };

        var setting = $.extend(defaults, options);

        var $this = this;

        loadPlayer($this, setting, function (player) {
            $this = $("#" + $this.attr("id"));
        });

        resizePlayer($this, settings.ratio);

        var isResizing = false;
        $(window).resize(function (e) {
            if (isResizing) {
                return;
            }

            resizePlayer($this, settings.ratio);
            
            isResizing = true;

            resizingTimer = setTimeout(function () {
                isResizing = false;
            }, 10);
        });
    }
})(jQuery);

使う側

<div id="player">
</div>

<script type="text/javascript">
$(function () {
	$("#player").youtubePlayer({
  	videoId: "seLF3oCjCv8"
  });
});
</script>