按下播放按钮后进行回调 - Youtube嵌入视频

时间:2011-11-16 13:58:06

标签: javascript jquery api youtube embed

按下播放按钮后是否可以执行javascript操作?我知道我需要在Youtube的API中使用onStateChange函数。但我真的不知道从哪里开始?有帮助吗?谢谢。

-

我也在这里找到了一些东西:http://apiblog.youtube.com/2011/01/introducing-javascript-player-api-for.html

4 个答案:

答案 0 :(得分:7)

这是一个您应该能够轻松扩展的解决方案:http://jsbin.com/evagof

答案 1 :(得分:4)

嘿,这是答案。 http://jsfiddle.net/masiha/4mEDR/ 享受......如果你有更多的qtns,请告诉我

答案 2 :(得分:3)

    <script src="http://www.google.com/jsapi" type="text/javascript"></script>
    <script type="text/javascript">
      google.load("swfobject", "2.1");
    </script>    
    <script type="text/javascript">
      // Update a particular HTML element with a new value
      function updateHTML(elmId, value) {
        document.getElementById(elmId).innerHTML = value;
      }


      // This function is called when the player changes state
      function onPlayerStateChange(newState) {
        updateHTML("playerState", newState);
        if(newState === 1){
            //if the player is now playing
            //add your code here
        }
      }

      // This function is automatically called by the player once it loads
      function onYouTubePlayerReady(playerId) {
        ytplayer = document.getElementById("ytPlayer");
        // This causes the updatePlayerInfo function to be called every 250ms to
        // get fresh data from the player
        setInterval(updatePlayerInfo, 250);
        updatePlayerInfo();
        ytplayer.addEventListener("onPlayerStateChange");
      }

      // The "main method" of this sample. Called when someone clicks "Run".
      function loadPlayer() {
        // The video to load
        var videoID = "ylLzyHk54Z0"
        // Lets Flash from another domain call JavaScript
        var params = { allowScriptAccess: "always" };
        // The element id of the Flash embed
        var atts = { id: "ytPlayer" };
        // All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
        swfobject.embedSWF("http://www.youtube.com/v/" + videoID + 
                           "?version=3&enablejsapi=1&playerapiid=player1", 
                           "videoDiv", "480", "295", "9", null, null, params, atts);
      }
      function _run() {
        loadPlayer();
      }
      google.setOnLoadCallback(_run);
    </script>
<div id="videoDiv">Loading...</div>
<p>Player state: <span id="playerState">--</span></p>

http://code.google.com/apis/ajax/playground/?exp=youtube#polling_the_player

答案 3 :(得分:2)

自从这个问题发布以来,也许Youtube做了一些改变,但大部分答案都没有奏效。我发现最简单的方法是使用iframe_api(https://developers.google.com/youtube/iframe_api_reference

这是一个例子

https://thimble.webmaker.org/en-US/project/39354/edit