Youtube встраивает iframe API playVideo () не работает в Firefox, когда видео находится в наложенном блоке

Я пытаюсь открыть и воспроизвести видео на YouTube в наложенном блоке. Проблема в том, что в Firefox метод playVideo() не работает, когда он вызывается из ссылки, которая также вызывает появление наложения (но он работает в Chrome). И наоборот, если я автоматически воспроизвожу видео, в Firefox оно запускается при появлении оверлея, а в Chrome — при загрузке исходной страницы. Как я могу получить решение, которое работает для обоих браузеров (и, возможно, для современного IE)?

Это код:

<!DOCTYPE html>
<html>
  <head>

  <style>
    .black_overlay{
        display: none;
        position: absolute;
        top: 0%;
        left: 0%;
        width: 100%;
        height: 100%;
        background-color: black;
        z-index:1001;
        -moz-opacity: 0.6;
        opacity:.60;
        filter: alpha(opacity=60);
    }
    .white_content {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        width: 660px;    
        height: 450px;
        margin-left: -330px;
        margin-top: -225px;
        padding: 16px;
        border: 1px solid orange;
        background-color: black;
        z-index:1002;
        overflow: auto;
    }  
  </style>
  </head>

  <body>

        <p>This is the main content. To display a lightbox click <a href = "javascript:void(0)" onclick = "showAndPlay();">here</a></p>
        <div id="light" class="white_content">
          This is the lightbox content.
          <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none';pauseVideo();">Close</a>
          <div id="player"></div>

        </div>
        <div id="fade" class="black_overlay"></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: 'M7lc1UVf-VE',
          //events: {
          //  'onReady': onPlayerReady, // If I uncomment this it works in Firefox but in Chrome the video starts at the page load
          //}
        });
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
      }
      function stopVideo() {
        player.stopVideo();
      }
      function pauseVideo() {
        player.pauseVideo();
      }
      function playVideo() {
        player.playVideo();
      }

      function showAndPlay() {
        document.getElementById('light').style.display='block';
        document.getElementById('fade').style.display='block';
        playVideo();
      }

    </script>  

  </body>
</html>

person Antonello    schedule 13.08.2014    source источник
comment
любопытно, вы на Mac? Я вижу некоторые странности в Mac Firefox для аналогичной проблемы.   -  person Simon_Weaver    schedule 07.01.2015
comment
@Simon_Weaver извините, нет, обычно я использую Linux. Я не могу на 100% вспомнить, когда у меня возникла эта проблема, но я думаю, что использовал Firefox и Chrome в Linux..   -  person Antonello    schedule 08.01.2015


Ответы (1)


Решено перемещение создания клиента YouTube в функцию, вызываемую при создании оверлея:

<!DOCTYPE html>
<html>
  <head>   
  <style>
    .black_overlay{
        display: none;
        position: absolute;
        top: 0%;
        left: 0%;
        width: 100%;
        height: 100%;
        background-color: black;
        z-index:1001;
        -moz-opacity: 0.6;
        opacity:.60;
        filter: alpha(opacity=60);
    }
    .white_content {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        width: 660px;    
        height: 450px;
        margin-left: -330px;
        margin-top: -225px;
        padding: 16px;
        border: 1px solid orange;
        background-color: black;
        z-index:1002;
        overflow: auto;
    }  
  </style>
  </head>

  <body>

        <p>This is the main content. To display a lightbox click <a href = "javascript:void(0)" onclick = "showAndPlay();">here</a></p>
        <div id="light" class="white_content">
          This is the lightbox content.
          <a href = "javascript:void(0)" onclick = "stopAndHide();">Close</a>
          <div id="player"></div>

        </div>
        <div id="fade" class="black_overlay"></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;

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
      }
      function stopVideo() {
        player.stopVideo();
      }
      function pauseVideo() {
        player.pauseVideo();
      }
      function playVideo() {
        player.playVideo();
      }

      function showAndPlay() {
        document.getElementById('light').style.display='block';
        document.getElementById('fade').style.display='block';
        if (!player){
          player = new YT.Player('player', {
            height: '390',
            width: '640',
            videoId: 'M7lc1UVf-VE',
            events: {
              'onReady': onPlayerReady,
            }
          });
        }
        playVideo();
      }

      function stopAndHide(){
        document.getElementById('light').style.display='none';
        document.getElementById('fade').style.display='none';   
        stopVideo(); 
      }    
    </script>  

  </body>
</html>
person Antonello    schedule 13.08.2014