如何检测浏览器已全屏显示

Bra*_*den 10 javascript

TLDR;

我可以通过全屏API检测浏览器是否已全屏显示,但我无法通过f11或浏览器菜单(特别是chrome)检测到浏览器已全屏显示.

原版的:

目前我正在使用screenfull进入全屏并检测到浏览器是全屏的.问题是,我不想显示我的全屏切换按钮时,浏览器(通过浏览器菜单即F11或全屏)通过浏览器功能去全屏.这是因为JavaScript的全屏API似乎并不能够检测到您在全屏或让你离开全屏当你通过浏览器功能去那里.我可以检测f11是否被击中,但这不适用于Mac或通过浏览器菜单启动全屏时.

有关如何检测是否通过浏览器功能启动全屏的任何想法?我只针对兼容webgl的浏览器,因此可以减少很多陷阱.

小智 9

我没有测试这个可靠性,但这是我的看法.

  //without jQuery
window.addEventListener('resize', function(){
  if(screen.width === window.innerWidth){
   // this is full screen
  }
});


  //with jQuery
$(document).ready(function() {
  $(window).on('resize', function(){
    if(screen.width === window.innerWidth){
      // this is full screen
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

当按下F11按钮和其他方法时,这似乎有效,因此它应该捕获全屏api没有的边缘情况.虽然我不确定screen.width与window.innerWidth的比较是检查全屏的可靠方法.也许其他人可以添加/批评这个.

  • 仅比较宽度是不够的,当窗口最大化时它是相同的.你必须比较高度,但乐趣从这里开始.在全屏Chromium中,屏幕高度和窗口高度是相同的,在IE中,它不是因为状态栏.我没有在firefox中尝试,但状态栏可以添加扩展名.在全屏中,窗口高度应小于屏幕尺寸的x%. (4认同)

Par*_*rth 6

fullscreenchange事件来检测全屏变事件,或者如果你不想来处理供应商前缀比你还可以收听到resize事件(窗口resize事件时进入或退出全屏也触发),然后检查是否document.fullscreenElement不为空确定全屏模式是否已打开.您需要相应的供应商前缀fullscreenElement.我会用这样的东西:

var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement ||
document.webkitFullscreenElement || document.msFullscreenElement;
Run Code Online (Sandbox Code Playgroud)

https://msdn.microsoft.com/en-us/library/dn312066(v=vs.85).aspx有一个很好的例子,我在下面引用它.他们使用了fullscreenChange事件,但你可以听取这个"resize"事件

document.addEventListener("fullscreenChange", function () {
          if (fullscreenElement != null) {
              console.info("Went full screen");
          } else {
              console.info("Exited full screen");              
          }
      });
Run Code Online (Sandbox Code Playgroud)

  • 这实际上不起作用,因为只有在调用HTML5全屏JavaScript API时才会触发`fullscreenChange`事件.如果用户点击F11,则该事件不会触发,并且`document.fullscreenElement`(和供应商前缀版本)仍为"null". (6认同)

Aru*_*ldd 6

在不同的浏览器和设备上尝试了很多方法之后,以下解决方案对我来说很可靠。

 window.addEventListener("resize", () => {
        setTimeout(() => {
            const windowWidth = window.innerWidth * window.devicePixelRatio;
            const windowHeight = window.innerHeight * window.devicePixelRatio;
            const screenWidth = window.screen.width;
            const screenHeight = window.screen.height;
            console.log(windowWidth/screenWidth);
            console.log(windowHeight/screenHeight);
            if (((windowWidth/screenWidth)>=0.95) && ((windowHeight/screenHeight)>=0.95)) {
                console.log("Fullscreen");
            }
            else {
                console.log("Not Fullscreen");
            }
        }, 100);
    })
Run Code Online (Sandbox Code Playgroud)

  • 为了确保您捕获放大/缩小的用户,请务必在组合中包含“window.devicePixelRatio”。应更改以下变量: `const windowWidth = window.innerWidth * window.devicePixelRatio;` `const windowHeight = window.innerHeight * window.devicePixelRatio;` (2认同)