7

I am trying to make a button that would toggle (on/off) HTML5 fullscreen on a certain website.

After reading plenty of documentation, it appears there still are some inconsistencies among how browsers treat certain properties for it.

I went for kind of "cross-browser" approach which does work in Firefox and Safari/MacOS, partially works in Safari/Windows and totally fails to work in Chrome and Opera.

Some castrated code snippets:

// class init
initialize: function() {

    this.elmButtonFullscreen = $('fullscreen');
    this.elmButtonFullscreen.on('click', this.onClickFullscreen.bindAsEventListener(this));
},

// helper methods
_launchFullScreen: function(element) {

    if(element.requestFullScreen) { element.requestFullScreen(); }
    else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); }
    else if(element.webkitRequestFullScreen) { element.webkitRequestFullScreen(); }
},
_cancelFullScreen: function() {

    if(document.cancelFullScreen) { document.cancelFullScreen(); }
    else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); }
    else if(document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); }
},
_isFullScreen: function() {

    fullScreen = document.fullscreenEnabled || document.mozFullscreenEnabled || document.webkitFullscreenEnabled ? true : false;
    if(this.debug) console.log('Fullscreen enabled? ' + fullScreen);
    return fullScreen;
},

// callbacks
onClickFullscreen: function(e) {

    e.stop();
    if(this._isFullScreen()) this._cancelFullScreen();
    else this._launchFullScreen(document.documentElement);
}
4

3 回答 3

5
function goFullScreen() {
  const el = document.documentElement,
      rfs = el.requestFullScreen
        || el.webkitRequestFullScreen
        || el.mozRequestFullScreen
        || el.msRequestFullscreen

  rfs.call(el)
}

document.querySelector('#full-screen-button')
  .addEventListener('click', () => {
    goFullScreen()
  })

Keep in mind that requesting fullScreen needs to be done via a user-triggered event such as a click event - mousedown,mouseup etc..

于 2014-02-23T22:56:57.563 回答
4

Changing the 1st line of _isFullScreen function to

fullScreen = document.fullscreenEnabled || document.mozFullscreenEnabled || document.webkitFullscreenEnabled ? true : false;

Does the trick (at least for Firefox, Chrome and Safari on Mac and Windows)

于 2013-05-04T07:55:12.310 回答
1

根据我在 Mozilla 的开发者网络上找到的内容,Webkit 的功能实际上拼写略有不同。

document.webkitRequestFullscreen用小写的“s”表示屏幕。

从 W3 spec 开始,它应该使用小写的“s”。

在 MDN 链接上,他们说:

注意:该规范使用标签“全屏”,如“requestFullscreen”或“fullscreenEnabled” - 没有大写的“s”。这里描述的实现和其他前缀实现可以使用大写的“S”。

于 2013-05-04T07:28:08.647 回答