悬停时播放多个 Plyr Vimeo 嵌入

Play multiple Plyr Vimeo embeds on hover

我在 Plyr.js 的页面上嵌入了多个视频。我的最终目标是让每个视频在悬停时播放并在没有悬停时停止。

这是我当前的代码:

const players = Array.from(document.querySelectorAll('#player')).map(p => new Plyr(p, {
  debug: true,
  volume: 0,
  controls: false,
  muted: true,
  fullscreen: { enabled: false },
  loop: { active: true },
  duration: 10
}));

$('#player').hover(playVideo, pauseVideo);
function playVideo(e){$(players, this).get(0).play();}
function pauseVideo(e){$(players, this).get(0).pause();}
.plyr{
  display:inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/plyr/3.4.7/plyr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="player" class="plyr__video-embed">
  <iframe src="https://player.vimeo.com/video/298038460?loop=1&byline=0&portrait=0&title=0&transparent=0" allowtransparency></iframe>
</div>
<div id="player" class="plyr__video-embed">
  <iframe src="https://player.vimeo.com/video/298038460?loop=1&byline=0&portrait=0&title=0&transparent=0" allowtransparency></iframe>
</div>

上面的代码在悬停时只播放第一个视频,不播放其他视频。

如果有人有任何建议,请随时分享。任何帮助将不胜感激。

第一个问题是重复的 id 值。它们必须是独一无二的。您已经为这些元素设置了 class (.plyr__video-embed),因此请改用它。

您的 hover 方法也尝试在悬停元素内找到播放器,但这不会起作用,因为 players 数组包含播放器插件的实例而不是 DOM 节点。

所以只需找到悬停元素的index在播放器节点中)并使用它来访问相关播放器。

const playerNodes = $('.plyr__video-embed');
const players = playerNodes.map((i,p) => new Plyr(p, {
  debug: true,
  volume: 0,
  controls: false,
  muted: true,
  fullscreen: { enabled: false },
  loop: { active: true }
})).get();

playerNodes.hover(playVideo, pauseVideo);

function playVideo(e){players[playerNodes.index(this)].play();}
function pauseVideo(e){players[playerNodes.index(this)].pause();}
.plyr {
  display: inline-block;
}

.plyr__video-embed {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/plyr/3.4.7/plyr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="plyr__video-embed">
  <iframe src="https://player.vimeo.com/video/298038460?loop=1&byline=0&portrait=0&title=0&transparent=0" allowtransparency></iframe>
</div>
<div class="plyr__video-embed">
  <iframe src="https://player.vimeo.com/video/298038460?loop=1&byline=0&portrait=0&title=0&transparent=0" allowtransparency></iframe>
</div>