Vue适配数据大屏

使用scale来实现适配多种屏幕,设计稿尺寸通常为1920*1080(默认尺寸16:9)

注:开发时可在浏览器中添加以下尺寸进行调试

常用尺寸: 1080P:1920*1080

2K:2560*1440

4K:3840*2160

8K:7680*4320

Html部分:

<template>
    <div class="appContent" ref="contentRef">
        <div>内容</div>
    </div>
</template>

Css部分:

.appContent{
    width: 1920px;
    height: 1080px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transform-origin: left top;
}

Js部分:

export default {
    data() {
        return {
           scale: {
            width:'1',
            height:'1'
           },
           scaleTime: null, // 定时任务
           baseWidth: 1920, // 设计稿尺寸
           baseHeight: 1080,  // 设计稿尺寸
           baseProportion: 0, // 比例
        }
    },
    created() { 
        this.baseProportion = parseFloat((this.baseWidth/this.baseHeight).toFixed(2));
    },
    mounted() {
        this.calcRate()
        window.addEventListener('resize', this.resize);
    },
    beforeDestroy () {
        window.removeEventListener('resize', this.resize);
    },
    methods: {
        // 计算放大倍数
       calcRate(){
            const contentRef = this.$refs.contentRef;
            if (!contentRef) return;
            // 当前宽高比
            const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(2));
            if (currentRate > this.baseProportion) {
                // 表示更宽
                this.scale.width = ((window.innerHeight * this.baseProportion) / this.baseWidth).toFixed(2);
                this.scale.height = (window.innerHeight / this.baseHeight).toFixed(2);
                contentRef.style.transform = `scale(${this.scale.width}, ${this.scale.height}) translate(-50%, -50%)`;
            } else {
                // 表示更高
                this.scale.height = ((window.innerWidth / this.baseProportion) / this.baseHeight).toFixed(2);
                this.scale.width = (window.innerWidth / this.baseWidth).toFixed(2);
                contentRef.style.transform = `scale(${this.scale.width}, ${this.scale.height}) translate(-50%, -50%)`;
            }
       },
       // 屏幕大小改变更新倍数
       resize () {
            clearTimeout(this.scaleTime)
            this.scaleTime = setTimeout(() => {
                this.calcRate()
            }, 0)
       }
    }
}

猜你喜欢

转载自blog.csdn.net/mi_ni123/article/details/128640025