Request Full Screen HTML5 Video onPlay

2020-03-04 06:42发布

问题:

I'm using the following code to trigger fullscreen when a user clicks on the play button on a <video> element:

var video = $("#video");
video.on('play', function(e){
    if (video.requestFullscreen) {
      video.requestFullscreen();
    } else if (video.mozRequestFullScreen) {
      video.mozRequestFullScreen();
    } else if (video.webkitRequestFullscreen) {
      video.webkitRequestFullscreen();
    }
});

But nothing happens when I click the play button.

Any idea's why?

EDIT: Here's my HTML code:

<video width="458" height="258" controls id='video' >
          <source src='<?= bloginfo('template_directory'); ?>/inc/pilot.mp4' type="video/mp4">
          <source src='<?= bloginfo('template_directory'); ?>/inc/pilot.ogv' type="video/ogg">
          <source src='<?= bloginfo('template_directory'); ?>/inc/pilot.webm' type="video/webm">
</video>

回答1:

There are a couple things going on here:

First, in your code, video is a jQuery object, not the actual video element. For a jQuery object, you can reference it like this:

var actualVideo = video[0]; // (assuming '#video' actually exists)

Second, for security and good user experience, browsers will only let you trigger full screen inside a user-triggered event, like a 'click'. You can't have every web page going to full screen as soon as you visit it, and you can cause a video to start playing automatically, which would violate that rule.

So an alternative solution would be to request fullscreen in a click event, like this:

var video = $("#video");
video.on('click', function(e){
    var vid = video[0];
    vid.play();
    if (vid.requestFullscreen) {
      vid.requestFullscreen();
    } else if (vid.mozRequestFullScreen) {
      vid.mozRequestFullScreen();
    } else if (vid.webkitRequestFullscreen) {
      vid.webkitRequestFullscreen();
    }
});

Ideally, you'd probably want to build out a more complete player ui, but this should give you the general idea.



回答2:

A less verbose way to toggle full screen combining answers from this and other questions.

This should handle all browser flavours: chromium- and webkit-based, firefox, opera, and MS-based browsers.

var p = document.querySelector('#videoplayer');

if (!window.isFs) {
    window.isFs = true;
    var fn_enter = p.requestFullscreen || p.webkitRequestFullscreen || p.mozRequestFullScreen || p.oRequestFullscreen || p.msRequestFullscreen;
    fn_enter.call(p);
} else {
    window.isFs = false;
    var fn_exit = p.exitFullScreen || p.webkitExitFullScreen || p.mozExitFullScreen || p.oExitFullScreen || p.msExitFullScreen;
    fn_exit.call(p);
}

p represents the DOM object of the video element, and window.isFs is just a random variable for storing the current fullscreen state.

If your player is a jQuery object then you can get the underlying DOM-element with var p = player.get(0).