實現原理:
使用css3 transform 實現指定盒子的等比放大/縮寫,通過js監聽窗口變動事件更新計算縮放比例,從而達到自適應屏幕的目的
上代碼:
import React from "react"; import Route from "@/route"; class App extends React.Component { constructor(props) { super(props); this.state = { center: { margin: 0, height: "100vh", overflow:"hidden" }, body: { width: "1920px", height: "1080px", }, }; } adaptation = () => { console.log("adaptation!!"); const w = document.documentElement.clientWidth; const h = document.documentElement.clientHeight; const l = 1920 / 1080; const width = h * l; const margin = (w - width) / 2 < 0 ? 0 : (w - width) / 2; const scale = h / 1080; this.setState(() => ({ center: { margin: `0 ${margin}px`, height: "100vh", overflow:"hidden" }, body: { transform: `scale(${scale}, ${scale})`, width: "1920px", height: "1080px", transformOrigin: "0 0", transition: "all 0.3s linear", }, })); }; componentDidMount() { this.adaptation(); window.addEventListener("resize", this.adaptation); } render() { return ( <div style={this.state.center}> <div style={this.state.body}> <Route></Route> </div> </div> ); } } export default App;
