页面加载后立即执行非工作功能

时间:2012-12-15 00:04:10

标签: javascript youtube-api youtube-javascript-api

demo中有一个Youtube无格式Javascript播放器。除非用户点击播放器下方的播放列表图片,否则标题和时间不会显示。要显示标题和时间,用户必须单击某些播放列表图像或必须等待改为下一个视频。我希望在第一次视频自动加载后不会点击任何内容来编写标题和时间。 javascript函数顺序可能有问题。除此之外,我什么都没想到。

以下所有代码都是为了帮助下一个人

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" lang="en"/>
<title>title</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js"></script>  

</head>
<body> 


<div class="ikinciSol">
                <a href="javascript:void(0);" onclick="play();">Play</a>
                -
                <a href="javascript:void(0);" onclick="pause();">Pause</a>
                -
                <a href="javascript:void(0);" onclick="stop();">Stop</a>
                <div id="videoTime">
                    <span id="videoCurrentTime"></span>
                    <span id="videoDuration"></span>
                </div>
                <div id="ytplayer_status"></div>
                <a name="ytplayer"></a>
<div id="ytplayer">You need Flash player 10+ and JavaScript enabled to view this video.</div>
<div id="ytplayer_div2"></div>


  <script type="text/javascript"> 
  //
  // YouTube JavaScript API Player With Playlist
  // http://911-need-code-help.blogspot.com/2009/10/youtube-javascript-player-with-playlist.html
  // Revision 2 [2012-03-24]
  //
  // Prerequisites
  // 1) Create following elements in your HTML:
  // -- a) ytplayer: a named anchor
  // -- b) ytplayer_div1: placeholder div for YouTube JavaScript Player
  // -- c) ytplayer_div2: container div for playlist
  // 2) Include SWFObject library from http://code.google.com/p/swfobject/
  //
  // Variables
  // -- ytplayer_playlist: an array containing YouTube Video IDs
  // -- ytplayer_playitem: index of the video to be played at any given time
  //
  var ytplayer_playlist = [ ];
  var ytplayer_playitem = 0;
  swfobject.addLoadEvent( ytplayer_render_player );
  swfobject.addLoadEvent( ytplayer_render_playlist );
  function ytplayer_render_player( )
  {
     swfobject.embedSWF
    (
      'http://www.youtube.com/apiplayer?video_id='+ ytplayer_playlist[ ytplayer_playitem ].videoid + '&enablejsapi=1&autoplay=1&loop=1&version=3&rel=0&fs=1&playerapiid=ytplayer',
      'ytplayer',
      '400',
      '225',
      '10',
      null,
      null,
      {
        allowScriptAccess: 'always',
        allowFullScreen: 'true'
      },
      {
        id: 'ytplayer'
      }
    );

  }

    // Update a particular HTML element with a new value
    function updateHTML(elmId, value) {
      var elem = document.getElementById(elmId);
      if(typeof elem !== 'undefined' && elem !== null) {
        document.getElementById(elmId).innerHTML = value;
      }
    }

//Converting seconds minute:second
function secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
return ((h > 0 ? h + ":" : "") + (m > 0 ? (h > 0 && m < 10 ? "0" : "") + m + ":" : "0:") + (s < 10 ? "0" : "") + s); }


// Display information about the current state of the player
function updatePlayerInfo() {
    // Also check that at least one function exists since when IE unloads the
    // page, it will destroy the SWF before clearing the interval.
    if(ytplayer && ytplayer.getDuration) {
        updateHTML("videoCurrentTime", secondsToHms(ytplayer.getCurrentTime())+' /');
        updateHTML("videoDuration", secondsToHms(ytplayer.getDuration()));
        updateHTML("bytesTotal", ytplayer.getVideoBytesTotal());
        updateHTML("startBytes", ytplayer.getVideoStartBytes());
        updateHTML("bytesLoaded", ytplayer.getVideoBytesLoaded());
        updateHTML("volume", ytplayer.getVolume());
    }
}

  function ytplayer_render_playlist( )
  {
    for ( var i = 0; i < ytplayer_playlist.length; i++ )
    {
      var img = document.createElement( "img" );
      img.src = "http://img.youtube.com/vi/" + ytplayer_playlist[ i ].videoid + "/default.jpg";
      var a = document.createElement( "a" );
      a.href = "#ytplayer";
      //
      // Thanks to some nice people who answered this question:
      // http://stackoverflow.com/questions/1552941/variables-in-anonymous-functions-can-someone-explain-the-following
      //
      a.onclick = (
        function( j )
        {
          return function( )
          {
            ytplayer_playitem = j;
            ytplayer_playlazy( 1000 );
          };
        }
      )( i );
      a.appendChild( img );
      document.getElementById( "ytplayer_div2" ).appendChild( a );
    }
  }
  function ytplayer_playlazy( delay )
  {
    //
    // Thanks to the anonymous person posted this tip:
    // http://www.tipstrs.com/tip/1084/Static-variables-in-Javascript
    //
    if ( typeof ytplayer_playlazy.timeoutid != 'undefined' )
    {
      window.clearTimeout( ytplayer_playlazy.timeoutid );
    }
    ytplayer_playlazy.timeoutid = window.setTimeout( ytplayer_play, delay );
  }
  function ytplayer_play( )
  {
    var o = document.getElementById( 'ytplayer' );
    if ( o )
    {
      o.loadVideoById( ytplayer_playlist[ ytplayer_playitem ].videoid );
      document.getElementById( "ytplayer_status" ).innerHTML = ytplayer_playlist[ ytplayer_playitem ].title;
      setInterval(updatePlayerInfo, 250);

    }
  }
  //
  // Ready Handler (this function is called automatically by YouTube JavaScript Player when it is ready)
  // * Sets up handler for other events
  //
  function onYouTubePlayerReady( playerid )
  {
    var o = document.getElementById( 'ytplayer' );
    if ( o )
    {
      o.addEventListener( "onStateChange", "ytplayerOnStateChange" );
      o.addEventListener( "onError", "ytplayerOnError" );
    }
  }
  //
  // State Change Handler
  // * Sets up the video index variable
  // * Calls the lazy play function
  //
  function ytplayerOnStateChange( state )
  {
    if ( state == 0 )
    {
      ytplayer_playitem += 1;
      ytplayer_playitem %= ytplayer_playlist.length;
      ytplayer_playlazy( 1000 );
    }
  }
  //
  // Error Handler
  // * Sets up the video index variable
  // * Calls the lazy play function
  //
  function ytplayerOnError( error )
  {
    if ( error )
    {
      ytplayer_playitem += 1;
      ytplayer_playitem %= ytplayer_playlist.length;
      ytplayer_playlazy( 1000 );
    }
  }
  //
  // Add items to the playlist one-by-one
  //
  ytplayer_playlist.push( 
  {
      videoid: 'tGvHNNOLnCk',
      title: 'title1'
  } 
  );
    ytplayer_playlist.push( 
  {
      videoid: '_-8IufkbuD0',
      title: 'title2'
  } 
  );
    ytplayer_playlist.push( 
  {
      videoid: 'wvsboPUjrGc',
      title: "title3"
  } 
  );
    ytplayer_playlist.push( 
  {
      videoid: '8To-6VIJZRE',
      title: 'title4'
  } 
  );
    ytplayer_playlist.push( 
  {
      videoid: '8pdkEJ0nFBg',
      title: 'title5'
  } 
  );



function play() {

  if (ytplayer) {

    document.getElementById('ytplayer').playVideo();

  }

}



function pause() {

  if (ytplayer) {

    document.getElementById('ytplayer').pauseVideo();

  }

}



function stop() {

  if (ytplayer) {

    document.getElementById('ytplayer').stopVideo();

  }

}


</script>


</body>
</html>

1 个答案:

答案 0 :(得分:1)

为什么你不包括:

document.getElementById( "ytplayer_status" ).innerHTML = ytplayer_playlist[ ytplayer_playitem ].title;

在您的更新功能中如下所示,我所做的更改是:

  • 我将set title函数添加到更新函数。
  • 我将setTimeout更新函数添加到body onload事件
  • ytplayer_play
  • 中取出设定的标题和超时时间

以下是更正:

http://jsfiddle.net/KpTaA/1/