window.onload=function(){
var videos = document.getElementsByTagName('video');//获取所有video
//循环给所有video添加监听事件 当前的video开始播时 调用pauseAll 将当前播放的video的索引传值过去
for (var i = videos.length - 1; i >= 0; i--) {
(function(n){
videos[n].addEventListener('play',function(){
pauseAll(n);
})
})(i)
}
//接收调用传来的索引 循环所有video 索引与传来的索引不相同的 暂停 重载
function pauseAll(index){
for (var j = videos.length - 1; j >= 0; j--) {
if (j!=index){
videos[j].pause();
videos[j].load();
}
}
};
}
vue
<div class='video-list'>
<div class="video-wrap" v-for="(item, index) in dataList" :key="index">
<div class="video">
<video :src="item.src" @play="handlePlay(index)" controls="controls">
您的浏览器不反对 video 标签。
</video>
</div>
</div>
</div>
data () {
videoElement: [] // 创立一个数组
},
mounted () {
this.videoElement = document.getElementsByTagName('video') // 获取页面上所有的video对象
},
handlePlay (index) {
const videoElement = this.videoElement
if (videoElement && videoElement.length > 0) {
for (let i = 0; i < videoElement.length; i++) {
if (i === index) {
this.videoElement[i].play()
} else {
this.videoElement[i].pause()
}
}
}
}