vue按键全屏和F11全屏共存

以下代码可直接复制
注意此段代码
// let element = document.documentElement // 当前页所有元素全屏
let element = document.getElementById(‘div1’) //让某个div元素全屏

<template>
  <div>
    <div style="width: 300px;height: 300px;background-color: cyan;" id="div1">
      vue按键全屏和F11全屏共存
      <br>
      <button @click="fullScreenFun">{{ fullScreen ? '退出全屏' : '全屏' }}按钮</button>
    </div>

    <div style="background-color: #f1ff;">其他无需全屏的内容</div>
  </div>
</template>

<script>
export default {
  name: "Screenfull",
  data() {
    return {
      fullScreen: false //是否全屏 默认否
    };
  },
  mounted() {
    // 监听onresize事件
    window.onresize = () => {
      console.log('检查当前是否全屏', this.checkFull());
      if (!this.checkFull()) {
        this.fullScreen = false;
      }
    };
    //监听按键事件
    window.addEventListener("keydown", this.KeyDown, true);
  },
  methods: {
    //监听解决F11打开后无法esc退出同时退出全屏的按钮也失效问题。
    KeyDown(event) {
      console.log("监听按键", event);
      if (event.keyCode === 122) {
        event.returnValue = false;
        this.fullScreenFun(); //这里是触发全屏的方法
      }
    },
    // 判断是否全屏模式
    checkFull() {
      //判断浏览器是否处于全屏状态 (需要考虑兼容问题)
      //火狐浏览器
      let isFull =
        document.mozFullScreen ||
        document.fullScreen ||
        //谷歌浏览器及Webkit内核浏览器
        document.webkitIsFullScreen ||
        document.webkitRequestFullScreen ||
        document.mozRequestFullScreen ||
        document.msFullscreenEnabled;
      if (isFull === undefined) {
        isFull = false;
      }
      return isFull;
    },
    // 全屏 退出全屏
    fullScreenFun() {
      // let element = document.documentElement // 当前页所有元素全屏
      let element = document.getElementById('div1') //让某个div元素全屏
      // 判断是否已经是全屏
      if (this.fullScreen) {
        // 如果是全屏,退出
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
          // 兼容火狐
          document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
          // 兼容谷歌等
          document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
          // 兼容IE
          document.msExitFullscreen();
        }
      } else {
        // 否则,进入全屏
        if (element.requestFullscreen) {
          element.requestFullscreen();
        } else if (element.webkitRequestFullScreen) {
          // 兼容谷歌等可以webkitRequestFullScreen也可以webkitRequestFullscreen
          element.webkitRequestFullScreen();
        } else if (element.mozRequestFullScreen) {
          // 兼容火狐
          element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
          // IE11
          element.msRequestFullscreen();
        }
      }
      this.fullScreen = !this.fullScreen;
    }
  }
};
</script>

你可能感兴趣的:(vue,vue按键全屏,F11全屏共存)