How can I add click-to-play to my HTML5 videos without interfering with native controls?

前端 未结 5 641
礼貌的吻别
礼貌的吻别 2021-01-04 01:49

I\'m using the following code to add click-to-play functionality to HTML5 video:

$(\'video\').click(function() {
  if ($(this).get(0).paused) {
    $(this).g         


        
5条回答
  •  粉色の甜心
    2021-01-04 02:07

    Torsten Walter's solution works well and it's a fairly elegant solution to the problem, and it's probably the best way to handle it, even if it doesn't handle click-to-pause. However, his solution got me thinking about a hacky way to do it, and I came up with this:

    Markup

     

    JavaScript

    $('#videocover').click(function(event) {
      var video = $('#myvideo')[0];
      if (video.paused) {
        video.play();
      }
      else {
        video.pause();
      }
      return false;
    });
    

    CSS

    #container {
      position: relative;
    }
    
    #videocover {
      position: absolute;
      z-index: 1;
      height: 290px; /* Change to size of video container - 25pxish */
      top: 0;
      right: 0;
      bottom: 0;
      left;
    }
    

    Basically, it keeps the clickable cover up all the time to handle the click-to-play/click-to-pause functionality, but makes sure the cover doesn't overlap with the controls at the bottom of the video.

    This is, of course a kludge, as it:

    • assumes all browsers place the controls in the same area, and that the controls are the same height
    • requires specifying the height of the video container in CSS
    • prevents the controls from appearing when the mouse hovers over the video

    But I figured I'd put it out there.

提交回复
热议问题