个别 UI 给到的数据化大屏设计稿是电脑屏幕的全屏分辨率 (即宽高 16:7 的占比),所以为了适应浏览器可视化窗口的比例,用transform: scale()
实现。
留神:固定了宽高比,所以窗口比例有余时,高低或左右会呈现空白区(可外层套个容器,给与大屏主色调相近的背景色)。
JS 写法:
// 设计稿宽高
const designDraftWidth = 1920; // 设计稿的宽度
const designDraftHeight = 1080; // 设计稿的高度
// 数据大屏自适应函数
const screenAdapt = () => {
// 获取可视化窗口宽高与屏幕大小宽高比
const wScale = window.innerWidth / designDraftWidth;
let hScale = window.innerHeight / designDraftHeight;
// 判断宽高比例,选较大的
let currentScale = wScale > hScale ? hScale : wScale;
// 给须要自适应的大屏增加款式
document.querySelector("#div").style = `width:${designDraftWidth}px;height:${designDraftHeight}px;transform:scale(${currentScale}) translate(-50%, -50%);position: absolute;left: 50%;top: 50%;-ms-transform-origin: 0 0;transform-origin: 0 0;overflow: hidden;background-size: 100% 100%;transition: 0.8s;`
}
// 初始化
screenAdapt();
// 监听屏幕变动
window.addEventListener('resize',screenAdapt);
React 写法
import React from "react";
// 设计稿宽高
const designDraftWidth = 1920; // 设计稿的宽度
const designDraftHeight = 1080; // 设计稿的高度
const Screen = (props) => {const [scale, setScale] = useState(0);// 宽高比
// 数据大屏自适应函数
const screenAdapt = () => {
// 获取可视化窗口宽高与屏幕大小宽高比
const wScale = window.innerWidth / designDraftWidth;
let hScale = window.innerHeight / designDraftHeight;
let currentScale = wScale > hScale ? hScale : wScale;
setScale(currentScale);
}
// 初始化
useEffect(() => {screenAdapt();
window.onresize = () => screenAdapt();
// 退出大屏后自适应隐没
return () => (window.onresize = null);
}, [])
return (
<div class="page">
<div
class="screenPage"
style={{transform: `scale(${scale}) translate(-50%, -50%)`,
width: designDraftWidth,
height: designDraftHeight
}}
>
</div>
</div>
)
}
export default Screen;
/* CSS 局部 */
.page {
background:#000;
.screenPage {
position: absolute;
left: 50%;
top: 50%;
transform-origin: 0 0;
overflow: hidden;
background-size: 100% 100%;
transition: 0.8s;
}
}