在youtube iframe嵌入游戏中发起一个事件

时间:2014-06-04 14:12:45

标签: javascript jquery youtube-api

我需要在播放youtube iframe时播放一个事件。因此,当按下播放按钮时,我需要调用一个函数来隐藏span.module-strip

我试过这个,但也许我走错了路?

$("#home-latest-vid")[0].onplay = function() {
    alert('hi');
};

HTML:

<div class="module module-home-video">

    <span class="module-strip">Latest Product Video</span>

        <iframe id="video" src="http://www.youtube.com/embed/RWeFOe2Cs4k?hd=1&rel=0&autohide=1&showinfo=0&enablejsapi=1" frameborder="0" width="640" height="360"></iframe>
</div>

3 个答案:

答案 0 :(得分:20)

<script src="https://www.youtube.com/iframe_api"></script>

<div class="module module-home-video">
    <span class="module-strip">Latest Product Video</span>
    <div id="video"></div>
</div>

<script>
    var player, playing = false;
    function onYouTubeIframeAPIReady() {
        player = new YT.Player('video', {
            height: '360',
            width: '640',
            videoId: 'RWeFOe2Cs4k',
            events: {
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerStateChange(event) {

      if (event.data == YT.PlayerState.PLAYING) {
         alert('video started');
         playing = true;
        }

      else if(event.data == YT.PlayerState.PAUSED){
            alert('video paused');
            playing = false;
       }
}
</script>

答案 1 :(得分:4)

您应该可以使用youtube javascript api,执行以下操作:

var ytplayer = null;

// event that will be fired when the player is fully loaded
function onYouTubePlayerReady(pid) {
   ytplayer = document.getElementById("ytplayer");
   ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
}

// event that will be fired when the state of the player changes
function onPlayerStateChange(state) {
  // check if it's playing
  if(state == 1) {
    // is playing
  }
}

要在嵌入式播放器中加载视频,请使用以下网址:

http://www.youtube.com/v/RWeFOe2Cs4k?version=3&enablejsapi=1

我还认为您应该可以像这样直接添加iframe

<iframe id="ytplayer" type="text/html" width="640" height="360" 
 src="https://www.youtube.com/embed/RWeFOe2Cs4k?enablejsapi=1"
 frameborder="0" allowfullscreen>

参考:Youtube Javascript Player API

答案 2 :(得分:1)

player.getPlayerState():Number 返回播放器的状态。

https://developers.google.com/youtube/iframe_api_reference

 /* 
      * player.getPlayerState():Number
      *
      * -1 – unstarted
      *  0 – ended
      * 1 – playing
      *  2 – paused
      *  3 – buffering
      *  5 – video cued
      *
      */
      function checkIfPlaying(){
        var playerStatus = player.getPlayerState();

         return  playerStatus == 1;
      }