我在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>
上面的代码仅在悬停时播放第一个视频,而不会播放其他视频。
如果有人有任何建议,请随时分享。任何帮助将不胜感激。
答案 0 :(得分:0)
第一个问题是重复的id
值。它们必须是唯一的。对于这些元素,您已经有一个类( .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>