yt api,jquery和分页-奇怪的行为

时间:2018-12-01 04:01:11

标签: javascript jquery youtube-javascript-api

我尝试制作带有多个iframe的视频墙,当用户将鼠标悬停在视频iframe上时,视频应该可以播放。 我在代码中设置的所有内容都可以正常工作-我可以调用currentPlayer.seekTo(10)并移动滑块,但currentPlayer.playVideo()不起作用。

最奇怪的是,如果我将鼠标悬停在卡片上-这会从数组中创建或选择一个播放器,并将其设置为全局变量,然后我通过控制台手动调用该播放器,

currentPlayer.playVideo() 

所有代码突然开始对该播放器起作用, 当我第一次在所有播放器上手动调用一个函数(无关紧要:playVideo,静音)时,我的网站开始按预期工作。我可以将鼠标悬停在视频之间,只有鼠标所在的位置可以正常工作。

html的代码部分在这里,但是在bin中根本不起作用,仅供参考。 https://jsbin.com/bavexujome/edit?html,js,output 我的js看起来像这样:

//yt api boilerplate

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

// my helper variables

var players = {}
var player
var currentPlayerId = null
var currentPlayer = null

// I have cards with iframes inside - when user hovers on a card 
// then I check if I have a player for that card in my players array 
//and if not I create it and set it to global variable
// I also try to start that video first time I got the autoplay 
// variable set - dont work and it there is a player I try to call
// .playvideo() on it - also does not work 
// all variables are set proper - I can console.log them

$(document).ready(function(){
  $('#hg-container').on("mouseenter", ".card", function(){
    currentPlayerId = $(this).find('iframe').attr('id');
    player = $(this).find('iframe')[0];

    if (!players[currentPlayerId]){
      players[currentPlayerId] = new YT.Player(player, {
        playerVars: { 'autoplay': 1 },
        events: {'onReady': onPlayerReady }
      });
    }
    else{
      currentPlayer = players[currentPlayerId]
      currentPlayer.playVideo();
    }
  });

  //when user leaves the card video should stop

  $('#hg-container').on("mouseleave", ".card", function(){
    currentPlayer.pauseVideo();
    currentPlayer = null;
  });
});

  //this gets called when video loads - and seekTo(10) works
  // but playVideo() don't

function onPlayerReady(event) {
  currentPlayer = players[currentPlayerId]
  currentPlayer.seekTo(10);
  currentPlayer.playVideo();
}

function onYouTubeIframeAPIReady(){
  console.log("ready")
}

任何提示吗?我认为这可能是一个范围问题,当我从js控制台调用此范围时,范围会有所更改,然后可以正常工作

0 个答案:

没有答案