如何使用 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>

輸出

更新於:2022年4月27日

6000+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.