#yyds干货盘点#数据化大屏自适应
  Qp5JTyIxtbwu 2023年11月19日 19 0

一般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;    
    }
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月19日 0

暂无评论

推荐阅读
Qp5JTyIxtbwu