HTML5 video - How do I make the whole video clickable?

谁都会走 提交于 2020-01-06 17:09:06

问题


Using a basic video, how do I make it play/pause when I click the video, instead of the controls?


回答1:


You can add a click handler to the entire video.

e.g.

<video id="my-video" controls src="myVideo.mp4"></video>

<script>    
   document.getElementById('my-video').addEventListener('click', function() {
       if (this.paused) {
          this.play();
       } else {
          this.pause();
       }
    });
</script>



回答2:


<video id="video1" onClick="playPause();">

...

    function playPause()
{ 
if (myVideo.paused) 
  myVideo.play(); 
else 
  myVideo.pause(); 
} 


<video id="video1" width="420">
    <source src="mov_bbb.mp4" type="video/mp4">
    <source src="mov_bbb.ogg" type="video/ogg">
    Your browser does not support HTML5 video.
  </video>

Source




回答3:


The details are in the Snippet's comments

// Reference #lid and #vid
var lid = document.getElementById('lid1');
var vid = document.getElementById('vid1');

// Listen for user to click #lid then...
lid.addEventListener('click', function(event) {

  // ...if #vid1 is paused, play video...
  if (vid.paused) {
    vid.play();

    // ...else pause video
  } else {
    vid.pause();
  }

  /* The only element that needs to know click
  | events is #iid, so stop the event chain from
  | continuing.
  */
  event.stopPropagation();
}, false);
.box {
  position: relative;
  min-width: 300px;
  min-height: 170px;
}
.lid {
  position: absolute;
  width: 100%;
  /* This measurement is just enough for #lid1 
  | to cover #vid1 and keep the controls exposed
  */
  min-height: calc(100% - 32px);
  z-index: 1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 32px;
  cursor: pointer;
}
.vid {
  position: absolute;
  height: auto;
  top: 0;
  left: 0;
}
<!--Parent positioned relative-->
<figure id='box1' class='box'>

  <!--#lid1 and #vid1 are positioned absolute-->
  <div id='lid1' class='lid'>

    <!--#vid1 is z-index:0 and #lid1 is z-index:1-->
    <video id="vid1" class="vid" src="http://html5demos.com/assets/dizzy.mp4" controls width='100%'></video>

  </div>

</figure>


来源:https://stackoverflow.com/questions/40282382/html5-video-how-do-i-make-the-whole-video-clickable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!