如何使用jQuery来播放/暂停视频

如何使用jQuery来播放/暂停视频

方法1:使用trigger()方法: trigger()方法用于执行一个指定的事件和事件的默认行为。要执行的事件被作为参数传递给这个方法。
播放 “事件用于播放任何媒体元素,同样,”暂停 “事件用于暂停任何媒体元素。使用这些事件和触发器()方法将按要求播放或暂停视频。

语法:

// Play the video
('#sample_video').trigger('play');
  
// Pause the video('#sample_video').trigger('pause');

示例:

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to play/pause video
        using JQuery?
    </title>
      
    <script src=
        "https://code.jquery.com/jquery-3.4.1.min.js">
    </script>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        Play/pause HTML 5 video
        using JQuery?
    </b>
      
    <p>
        Click on the buttons to play
        or pause the video.
    </p>
      
    <button onclick="playVideo()">
        Play Video
    
      
    <button onclick="pauseVideo()">
        Pause Video
    
    <br>
      
    <video id="sample_video" width="360" height="240">
      
        <source src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200107020629/sample_video.mp4"
                type="video/mp4">
    </video>
      
    <script>
        function playVideo() {
            ('#sample_video').trigger('play');
        }
        function pauseVideo() {
            ('#sample_video').trigger('pause');
        }
    </script>
</body>
  
</html>

输出:
如何使用jQuery来播放/暂停视频?

方法2:使用play()和pause()方法: JavaScript中的play()方法是用来尝试播放一个媒体文件的。在jQuery中,首先使用选择器选择视频文件,然后使用get()方法选择实际元素。然后在这个元素上使用play()方法来尝试开始播放视频。

JavaScript中的pause()方法是用来暂停一个媒体文件的播放。在jQuery中,首先使用选择器选择视频文件,然后使用get()方法选择实际元素。然后在这个元素上使用pause()方法来暂停视频。

语法:

// Play the video
('#sample_video').get(0).play();
  
// Pause the video('#sample_video').get(0).pause();

示例:

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to play/pause video
        using JQuery?
    </title>
      
    <script src=
        "https://code.jquery.com/jquery-3.4.1.min.js">
    </script>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        Play/pause HTML 5 video
        using JQuery?
    </b>
      
    <p>
        Click on the buttons to play
        or pause the video.
    </p>
      
    <button onclick="playVideo()">
        Play Video
    
      
    <button onclick="pauseVideo()">
        Pause Video
    
    <br>
      
    <video id="sample_video" width="360" height="240">
        <source src=
"https://media.geeksforgeeks.org/wp-content/uploads/20200107020629/sample_video.mp4"
                type="video/mp4">
    </video>
      
    <script>
        function playVideo() {
            ('#sample_video').get(0).play();
        }
      
        function pauseVideo() {
            ('#sample_video').get(0).pause();
        }
    </script>
</body>
  
</html>

输出:
如何使用jQuery来播放/暂停视频?

jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程