前端vue实现全屏和按esc退出全屏功能

效果如下:
前端vue实现全屏和按esc退出全屏功能_第1张图片
前端vue实现全屏和按esc退出全屏功能_第2张图片

不多说,直接上代码如下,复制即可使用,注意图片位置修改即可:

1、vue页面中根据是否全屏判断当前显示图片或icon图标,isFullScren为true时表示全屏,默认值为false,并绑定click事件

 
            

2、click全屏事件

 data() {
    return {
      isFullScren:false,
      quanping:require('@/assets/img/header/quanping.png'),
      tuichuquanping:require('@/assets/img/header/tuichuquanping.png')
     }
 }

methods: {
    fullScreenEvent() {
      let el = document.documentElement;
      if (this.isFullScren) {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        }
      } else {
        if (el.requestFullscreen) {
          el.requestFullscreen();
        } else if (el.mozRequestFullScreen) {
          el.mozRequestFullScreen();
        } else if (el.webkitRequestFullScreen) {
          el.webkitRequestFullScreen();
        } else if (el.msRequestFullscreen) {
          el.msRequestFullscreen();
        }
      }
    },
}

3、 页面初始化渲染完成后,绑定fullscreenchange的全屏改变监听事件,这样按esc退出全屏时也会触发

mounted() {
    let isFullscreen =
      document.fullscreenElement ||
      document.mozFullScreenElement ||
      document.webkitFullscreenElement ||
      document.fullScreen ||
      document.mozFullScreen ||
      document.webkitIsFullScreen;
      isFullscreen = !!isFullscreen;
    let that = this;
    document.addEventListener("fullscreenchange", () => {
      that.isFullScren = !that.isFullScren;
    });
    document.addEventListener("mozfullscreenchange", () => {
      that.isFullScren = !that.isFullScren;
    });
    document.addEventListener("webkitfullscreenchange", () => {
      that.isFullScren = !that.isFullScren;
    });
    document.addEventListener("msfullscreenchange", () => {
      that.isFullScren = !that.isFullScren;
    });
},

你可能感兴趣的:(全屏,退出全屏,vue,按esc)