Request Full Screen HTML5 Video onPlay

前端 未结 2 1157
忘掉有多难
忘掉有多难 2021-01-06 11:08

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

var video = $(\"#video\");         


        
相关标签:
2条回答
  • 2021-01-06 11:32

    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.

    0 讨论(0)
  • 2021-01-06 11:51

    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).

    0 讨论(0)
提交回复
热议问题