Possible to add an onclick event to a YouTube iframe?

后端 未结 1 1356
猫巷女王i
猫巷女王i 2021-01-14 10:51

I\'ve got a site with an HTML5 audio player and embedded YouTube music videos. I\'d like to make it so that when the user clicks on a YouTube video to play it the music will

相关标签:
1条回答
  • 2021-01-14 11:28

    You should use the YouTube IFrame API. Add an event listener for onStateChange to get notified when the player's state changes. See the sample code below.

    <!DOCTYPE html>
    <html>
      <head>
        <script src="https://www.youtube.com/iframe_api"></script>
      </head>
      <body>
        <div id='vidWrapper'>
          <!-- The <iframe> (and video player) will replace this <div> tag. -->
          <div id="ytplayer"></div>
        </div>
    
        <script>
          var player;
    
          function onYouTubeIframeAPIReady() {
            player = new YT.Player('ytplayer', {
              height: '390',
              width: '640',
              videoId: 'M7lc1UVf-VE',
              events: {
                'onStateChange': function(event) {
                  if (event.data == YT.PlayerState.PLAYING) {
                    pauseAudio();
                  }
                }
              }
            });
          }
    
          function pauseAudio() {
            ...
          }
        </script>
      </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题