如何使用 JavaScript 在鼠标悬停时播放视频,鼠标移出时暂停?
在本文中,我们将探讨 **事件监听器** 以及如何使用它们来暂停和播放视频。我们将使用鼠标悬停和鼠标移出事件来控制视频。
本文的主要内容包括:当鼠标悬停在视频上时播放视频,当鼠标移出该 div 时停止/暂停视频。
为了实现此特定目的,我们将使用 **JavaScript** 来记录事件并播放/暂停视频。
方法
我们将把视频附加到我们的 HTML DOM 元素,然后应用鼠标悬停和鼠标移出事件监听器。每当 DOM 监听此事件时,它将触发 JavaScript 函数,该函数将告诉模板启动或停止视频。
示例
在下面的示例中,我们使用鼠标事件监听器在需要时播放和暂停视频。
index.html
<!DOCTYPE html> <html lang="en"> <head> <title>Playing/Pausing Video</title> <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> <h1 style="color: green;">Welcome to Tutorials Point</h1> <!-- Video element --> <video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" muted class="vid" loop style="border: solid; width: 550px;"> </video> <script> // Listening to the video element let clip = document.querySelector(".vid") /* Adding the event listeners on the video to play/pause the video. */ clip.addEventListener("mouseover", function (e) { clip.play(); }) /* Applying the mouse out event to pause the video */ clip.addEventListener("mouseout", function (e) { clip.pause(); }) </script> </body> </html>
输出

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP