美文网首页全栈笔记
JS 全屏和退出全屏

JS 全屏和退出全屏

作者: 小贤笔记 | 来源:发表于2022-08-05 15:53 被阅读0次

    进入全屏

    function full(ele) {
          if (ele.requestFullscreen) {
              ele.requestFullscreen();
          } else if (ele.mozRequestFullScreen) {
              ele.mozRequestFullScreen();
          } else if (ele.webkitRequestFullscreen) {
              ele.webkitRequestFullscreen();
          } else if (ele.msRequestFullscreen) {
              ele.msRequestFullscreen();
          }
    }
    

    退出全屏

    function exitFullscreen() {
        if(document.exitFullScreen) {
            document.exitFullScreen();
        } else if(document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if(document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if(document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
    

    获取当前全屏的节点

    function getFullscreenElement() {
        return (        
            document.fullscreenElement ||
            document.mozFullScreenElement ||
            document.msFullScreenElement ||
            document.webkitFullscreenElement||null
        );
    }
    

    判断当前是否全屏

    function isFullScreen() {
      return  !! (
          document.fullscreen || 
          document.mozFullScreen ||                         
          document.webkitIsFullScreen ||       
          document.webkitFullScreen || 
          document.msFullScreen 
       );
    }
    

    判断当前文档是否能切换到全屏

    function isFullscreenEnabled() {
        return  (
            document.fullscreenEnabled ||
            document.mozFullScreenEnabled ||
            document.webkitFullscreenEnabled ||
            document.msFullscreenEnabled
        );
    }
    

    全屏事件

    document.addEventListener('fullscreenchange', evt => {
        if (document.fullscreenElement) {
            console.log('进入全屏')
        } else {
            console.log('退出全屏')
        }
    })
    

    注:
    1.document下没有requestFullscreen
    2.requestFullscreen方法只能由用户触发,比如:在onload事件中不能触发
    3.页面跳转需先退出全屏
    4.进入全屏的元素,将脱离其父元素,所以可能导致之前某些css的失效
    解决方案:使用 :full-screen伪类 为元素添加全屏时的样式(使用时为了兼容注意添加-webkit、-moz或-ms前缀)
    5.一个元素A全屏后,其子元素要再全屏,需先让元素A退出全屏

    相关文章

      网友评论

        本文标题:JS 全屏和退出全屏

        本文链接:https://www.haomeiwen.com/subject/htppwrtx.html