JavaScript 如何在鼠标悬停时播放视频,鼠标离开时暂停
本文介绍了如何在鼠标悬停在视频上时播放视频,并在将鼠标从视频元素移除时停止播放视频。有时我们希望网站上的视频在用户将鼠标悬停在上面时自动开始播放,因为这样可以减少用户在网站上的点击次数,并为用户提供很好的体验。因此,我们使用JavaScript来实现在鼠标悬停在视频上时可播放,当鼠标离开时自动停止播放的目的。
方法: 首先,我们会将一个视频文件附加到HTML DOM上,然后使用JavaScript在其上应用mouseover和mouseout事件监听器。下面是完整的代码实现:
示例: 在这个示例中,我们将使用纯JavaScript来播放视频。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
</head>
<body>
<!-- Video element -->
<video src=
"https://media.geeksforgeeks.org/wp-content/uploads/20210810214359/2.mp4"
type="video/mp4" muted class="vid"
loop style="border: solid; width: 800px;">
</video>
<script>
// Targeting video element
let clip = document.querySelector(".vid")
/* Applying mouseover event on video clip
and then we call play() function to play
the video when the mouse is over the video */
clip.addEventListener("mouseover", function (e) {
clip.play();
})
/* Applying mouseout event on video clip
and then we call pause() function to stop
the video when the mouse is out the video */
clip.addEventListener("mouseout", function (e) {
clip.pause();
})
</script>
</body>
</html>