Possible to add an onclick event to a YouTube iframe?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-19 10:01:23

问题


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 stop. Wrapping the iframe in

<div id='vidWrapper' onclick='pauseAudio()'>YT stuff</div>

works for the sliver of pixels outside of the iframe, but not when you click on the actual video. Anyone have any ideas?


回答1:


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>


来源:https://stackoverflow.com/questions/29640675/possible-to-add-an-onclick-event-to-a-youtube-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!