一般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;
}
}