首页 > 解决方案 > Youtube API 在重播时触发 onplayerstatechange 两次?

问题描述

我注意到我正在处理的项目中有一些奇怪的行为,所以我决定隔离我的变量并直接从 youtube iframe API 文档中获取基本代码,我仍然看到同样的事情。当我的视频第一次播放时,一切正常。但是,如果我点击“重播”按钮,onPlayerStateChange (with event.data==1 / "playing") 会触发两次,就在彼此之上。知道为什么会发生这种情况,以及如何让“播放”的“playerstatechange”在重播时只触发一次?

    <!DOCTYPE html>
<html>
  <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
        <div id="player"></div>

    <script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'cOgj_5lYijo',
          events: {
            'onStateChange': onPlayerStateChange
          }
        });
      }

      // 5. The API calls this function when the player's state changes.
      function onPlayerStateChange(event) {
        if(event.data==1){
        console.log("onplayerstate change happening: ",event)}
      }

    </script>
  </body>
</html>

标签: youtube-apiyoutube-iframe-api

解决方案


推荐阅读