简体   繁体   中英

JavaScript: How to toggle HTML5 video fullscreen / non-fullscreen?

Given is an HTML5 video element. A button should change this video element into fullscreen, or end the fullscreen.

I have already written a JavaScript function. This works fine in Firefox . Unfortunately, the function does not work in Google Chrome.

function toggleFullScreen() {
    var player = document.querySelector('#playerContainer');
    if (!document.mozFullScreen && !document.webkitFullScreen) {
        if (player.mozRequestFullScreen) {
            player.mozRequestFullScreen();
        } 
        else {
            player.webkitRequestFullScreen();
        }
    } else {
        if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else {
            document.webkitCancelFullScreen();
        }
    }
}

While everything works fine in Firefox , in Chrome , the window is positioned only in the middle of the full-screen window. Also, Chrome can not quit the fullscreen.

I used Firefox Quantum 61.0.1 and Google Chrome 68.0 .

I see a note in devdocs, maybe useful for you:

It's worth noting a key difference here between the Gecko and WebKit implementations at this time: Gecko automatically adds CSS rules to the element to stretch it to fill the screen: width: 100%; height: 100% width: 100%; height: 100%

WebKit doesn't do this. Instead, it centers the fullscreen element at the same size in a screen that's otherwise black. To get the same fullscreen behavior in WebKit, you need to add your own " width: 100%; height: 100%; " CSS rules to the element yourself:

#myvideo:-webkit-full-screen {
    width: 100%;
    height: 100%;
}

I solved my problem... it failed because I used the wrong function in the first if-statement:

Wrong:

if (!document.mozFullScreen && !document.webkitFullScreen) { ... }

Correct:

if (!document.mozFullScreen && !document.webkitIsFullScreen) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM