上下文:
我 GetElementsByClassName ,保存到变量中,然后循环浏览页面上的所有视频,并使用适当的 play()/ pause()添加 EventListeners >功能->对于'mouseover'视频预览来说效果很好。
当我在按钮上'mouseover'时,视频停止,并且出现“ Uncaught TypeError:e.target.play在HTMLDivElement.videoPlay上不起作用” 我的控制台错误。
在控制台中进行测试时,可以使用以下适当的索引播放每个视频: buttons [0] .nextElementSibling.play()
但是由于某种原因,我无法使其在该函数中起作用。
关于如何使其工作的任何想法?
HTML
<div>
<!-- Video segment -->
<div class="vid-segment">
<a class="vid-btn" href="#">
<i class="fa fa-shopping-cart"></i>
<span>Add to cart</span>
</a>
<video class="video-preview" witdh="352" height="198" muted>
<source src="static/videos/video1.mov" type="video/mp4">
</video>
</div>
<!-- Video segment end -->
<!-- Video segment -->
<div class="vid-segment">
<a class="vid-btn" href="#">
<i class="fa fa-shopping-cart"></i>
<span>Add to cart</span>
</a>
<video class="video-preview" witdh="352" height="198" muted>
<source src="static/videos/video1.mov" type="video/mp4">
</video>
</div>
<!-- Video segment end -->
JavaScript
function videoPlay() {
loop = true;
play()
console.log("Video plays")
}
function videoStop() {
currentTime = 0;
pause()
console.log("Video stops")
}
const videos = document.getElementsByClassName('.vid-segment')
const buttons = document.getElementsByClassName('.vid-btn')
for(var i = 0; i < videos.length; i++) {
videos[i].addEventListener('mouseover', videoPlay);
videos[i].addEventListener('mouseout', videoStop);
buttons[i].addEventListener('mouseover', function() {
buttons[i].nextElementSibling.play()
})
}
答案 0 :(得分:1)
我知道了!答案如下:
const videos = document.querySelectorAll('.video-preview')
const buttons = document.querySelectorAll('.vid-btn')
for (let i = 0; i < videos.length; i++) {
videos[i].addEventListener('mouseover', function() {
console.log('play')
videos[i].play()
})
videos[i].addEventListener('mouseout', function() {
console.log('pause')
videos[i].pause()
videos[i].currentTime = 0;
})
buttons[i].addEventListener('mouseover', function() {
console.log('button hover')
videos[i].play();
})
buttons[i].addEventListener('mouseout', function() {
console.log('button hover')
videos[i].pause()
videos[i].currentTime = 0;
})
}