结合useRef() hook实现按F11进入全屏

最近做react项目碰到个需求:将内容区域全屏现实
浏览器为谷歌浏览器

核心api:

  • useRef() // 类似于React.createRef()
  • el.webkitRequestFullScreen() // 全屏

废话少说,直接上代码:

import React, { useRef, useEffect } from 'react'
import { Layout, Breadcrumb, message } from 'antd'
import style from './index.less'

export default function Home() {
  const contentRef: any = useRef()  // 创建ref对象,下面jsx中的ref={contentRef}就是在给这个ref对象赋值,值为被ref附着的dom对象,也就是class="content"的那个div
  useEffect(() => {
    message.info('按F11可进入全屏')
    document.addEventListener('keydown', function (e) {
      contentRef.current.focus()
      if (e && e.key == 'F11') {
        contentRef.current.style.padding = '24px'
        contentRef.current.style.margin = '0px'
        //捕捉F11键盘动作
        e.preventDefault();  //阻止F11默认动作
        var el = contentRef.current
        var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;//定义不同浏览器的全屏API
        //执行全屏
        if (typeof rfs != "undefined" && rfs) {
          rfs.call(el);
        } else if (typeof window.ActiveXObject != "undefined") {
          var wscript = new ActiveXObject("WScript.Shell");
          if (wscript != null) {
            wscript.SendKeys("{F11}");
          }
        }
      }
    })
  }, []) // 空数组表示副作用只在组件componentDidMount生命周期会执行一次
  return (
    <>
      <Breadcrumb style={{ margin: '16px 0' }}>
        <Breadcrumb.Item>首页</Breadcrumb.Item>
      </Breadcrumb>
      <Content className={style['site-layout-background']} style={{ padding: 24, margin: 0, minHeight: 280, }}>
      	<div className={style.content} ref={contentRef}>
      	 ......
        </div>
      </Content>
    </>
  )
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值