YouTube Player APIを利用してYouTubeの埋め込み動画にオリジナルの再生ボタンと一時停止ボタンを実装する方法(iframeタグを使用)のデモページ

※デベロッパーツール等でソースコードをご確認ください(Please check using Developer tools)

マイナビAGENT

スポンサーリンク

無料で登録するだけで、最高5,000万円の損害賠償が付く!

CSS

.wrap {
  width: 640px;
  margin: 50px auto 0;
  text-align: center;
}

.movie {
  position: relative;
  width: 100%;
  padding-top: 56.25%;
}

.movie iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

#play {
  display: inline-block;
  position: relative;
  width: 1em;
  height: 1em;
  margin: 30px 0 0;
  border: 0.05em solid #000;
  border-radius: 50%;
  color: #000;
  font-size: 75px;
  cursor: pointer;
}
#play:before {
  content: "";
  position: absolute;
  top: 50%;
  left: 30%;
  transform: translateY(-50%);
  width: 0px;
  height: 0px;
  border: 0.3em solid transparent;
  border-left: 0.5em solid #000;
  box-sizing: border-box;
}

#pause {
  position: relative;
  display: inline-block;
  width: 1em;
  height: 1em;
  margin: 30px 0 0;
  border: 0.05em solid #000;
  border-radius: 50%;
  color: #000;
  font-size: 75px;
  cursor: pointer;
}
#pause:before,
#pause:after {
  content: "";
  position: absolute;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  width: 0.1em;
  height: 0.5em;
  box-sizing: border-box;
  background: #000;
}
#pause:before {
  left: 40%;
}
#pause:after {
  left: 60%;
}
@media screen and (max-width:640px) {
  .wrap {
    width: 100%;
  }
}
  

JavaScript

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
  player = new YT.Player("player", {
    events: {
      onReady: onPlayerReady
    }
  });
}
function onPlayerReady(event) {
  var playButton = document.getElementById("play");
  playButton.addEventListener("click", function () {
    player.playVideo();
  });

  var pauseButton = document.getElementById("pause");
  pauseButton.addEventListener("click", function () {
    player.pauseVideo();
  });
}