Video.js 自动生成多个播放器,实现单播放控制
以下是基于 Video.js 的代码示例,您可以根据需要自行修改:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>VideoJS Example</title>
<link href='https://vjs.zencdn.net/7.11.4/video-js.css' rel='stylesheet'>
<script src='https://vjs.zencdn.net/7.11.4/video.min.js'></script>
</head>
<body>
<div id='video-container'>
<video id='video-1' class='video-js' controls preload='auto' width='640' height='264'>
<source src='http://vjs.zencdn.net/v/oceans.mp4' type='video/mp4'>
</video>
<video id='video-2' class='video-js' controls preload='auto' width='640' height='264'>
<source src='http://vjs.zencdn.net/v/oceans.mp4' type='video/mp4'>
</video>
<!-- add more videos here -->
</div>
<script>
// create an array to store all video players
var players = [];
// create 10 video players and push them into the array
for (var i = 1; i <= 10; i++) {
var player = videojs('video-' + i);
players.push(player);
}
// add event listener to each player
players.forEach(function(player) {
player.on('play', function() {
// pause all other players when one player starts playing
players.forEach(function(otherPlayer) {
if (otherPlayer !== player && !otherPlayer.paused()) {
otherPlayer.pause();
}
});
});
});
</script>
</body>
</html>
在上面的代码中,我们首先创建了一个包含 10 个 video 元素的容器。然后,我们使用 for 循环创建了 10 个 videojs 播放器,并将它们存储在一个数组中。
接下来,我们遍历每个播放器,并将一个 play 事件监听器添加到它们上面。当播放器开始播放时,该事件监听器会暂停所有其他播放器。
这样,当一个播放器开始播放时,其他的就会自动停止。
原文地址: https://www.cveoy.top/t/topic/nnis 著作权归作者所有。请勿转载和采集!