填坑:操作div全屏时踩下的雷区

在Vue项目中,作者遇到了一个需求,需要将包含多个表格的页面实现全屏显示。在尝试使用requestFullscreen API实现div全屏时,遇到了'Illegal invocation'的错误。错误的原因是调用环境上下文不正确,解决方案是通过bind、call或apply确保函数调用的正确上下文。文章详细记录了问题的解决过程,对于遇到类似问题的前端开发者具有参考价值。
摘要由CSDN通过智能技术生成

操作div全屏时踩下的雷区

前言

最近在公司开发一个项目,其中一个页面展示了三个表格,而且其中的一个表格需要展示40多个字段。看到需求的时候,瞬间无语了。但是作为一个合格的打工人,不管需求多么奇葩,东西总要给人做出来的。因此想到,每个表格都可以让它放到最大。表格的展示的列可以控制。
在实现div全屏时遇到一个问题,记录于此。

正文
<template>
  <div class="fullscreen">
      <div class="fullscreen-header">
          <div class="fullscreen-btn">
              <button @click="handleClick">{{isFullAllScreen?"还原":"全屏"}}</button>
          </div>
      </div>
      <div class="fullscreen-wrap">
          <slot></slot>
      </div>
  </div>
</template>

<script>
export default {
  name: 'full-screen',
  data () {
    return {
      isFullAllScreen: false
    }
  },
  methods: {
    handleClick (e) {
      console.log(e)
      e.stopPropagation()
      this.isFullAllScreen ? this.exitFullScreen() : this.setDomFullScreen(this.$el)
    },
    setDomFullScreen (el) {
      const rfs = el.requestFullscreen || el.webkitRequestFullScreen
      if (rfs) {
        rfs().then(a => {
          console.log(a)
          this.isFullAllScreen = true
        }).catch(e => {
          console.log(e)
        })
      }
    },
    exitFullScreen () {
      if (document.exitFullscreen) {
        document.exitFullscreen()
        this.isFullAllScreen = false
      }
    }
  }
}
</script>

<style>
 .fullscreen{
     position: static;
 }
 .fullscreen-header{
     position: relative;
     overflow: visible;
 }
 .fullscreen-btn{
     position: absolute;
     top: 10px;
     right: 10px;
     z-index: 40;
 }
.fullscreen-wrap{
    position: relative;
}
</style>

点击按钮时报错:

TypeError: Failed to execute 'requestFullscreen' on 'Element': Illegal invocation
    at Proxy.setDomFullScreen (FullScreen.vue?30ea:31)
    at Proxy.handleClick (FullScreen.vue?30ea:26)
    at onClick._cache.<computed>._cache.<computed> (FullScreen.vue?30ea:5)
    at callWithErrorHandling (runtime-core.esm-bundler.js?5c40:154)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?5c40:163)
    at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?830f:301)

原因竟然是:

运行环境上下文绑定问题;
组件中rfs的调用者已经不是el.
解决方法:
使用bind函数,或者call、apply方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值