前端大屏自适应

757 阅读1分钟

image.png

仔细观察网易有数百度suger,他们都采用了css3的缩放transform: scale(X)属性,看到这是不是有种豁然开朗的感觉。
于是我们只要监听浏览器的窗口大小,然后控制变化的比例就好了。

以React的写法为例

getScale=() => {
    // 固定好16:9的宽高比,计算出最合适的缩放比,宽高比可根据需要自行更改
    const {width=1920, height=1080} = this.props
    let ww=window.innerWidth/width
    let wh=window.innerHeight/height
    return ww<wh?ww: wh
}
setScale = debounce(() => {
    // 获取到缩放比,设置它
    let scale=this.getScale()
    this.setState({ scale })
}, 500)

监听window的resize事件最好加个节流函数debounce

window.addEventListener('resize', this.setScale)

然后一个简单的组件就封装好了

import React, { Component } from 'react';
import debounce from 'lodash.debounce'
import s from './index.less'

class Comp extends Component{
  constructor(p) {
    super(p)
    this.state={
      scale: this.getScale()
    }
  }
  componentDidMount() {
    window.addEventListener('resize', this.setScale)
  }
  getScale=() => {
    const {width=1920, height=1080} = this.props
    let ww=window.innerWidth/width
    let wh=window.innerHeight/height
    return ww<wh?ww: wh
  }
  setScale = debounce(() => {
    let scale=this.getScale()
    this.setState({ scale })
  }, 500)
  render() {
    const {width=1920, height=1080, children} = this.props
    const {scale} = this.state
    return(
      <div
        className={s['scale-box']}
        style={{
          transform: `scale(${scale}) translate(-50%, -50%)`,
          WebkitTransform: `scale(${scale}) translate(-50%, -50%)`,
          width,
          height
        }}
      >
        {children}
      </div>
    )
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.setScale)
  }
}

export default Comp

样式文件index.less

.scale-box{
  transform-origin: 0 0;
  position: absolute;
  left: 50%;
  top: 50%;
  transition: 0.3s;
}

只要把页面放在这个组件中,就能实现跟大厂们类似的效果。这种方式下不管屏幕有多大,分辨率有多高,只要屏幕的比例跟你定的比例一致,都能呈现出完美效果。而且开发过程中,样式的单位也可以直接用px,省去了转换的烦恼~~~
最后附上npm链接:www.npmjs.com/package/rea…