前端自适应缩放解决方案

文章介绍了一种方法,通过CSS和JavaScript实现基于1920*1080设计稿的等比例缩放页面,确保在不同设备上保持高还原度。利用Vue.js监听窗口大小变化,动态调整缩放比例,保持固定的16:9宽高比,从而保证布局的适应性。
摘要由CSDN通过智能技术生成

设计师以1920*1080 比例给出设计稿, 需要高还原度实现效果可以使用等比例缩放页面方案,具体代码如下

  html,
    body {
        background: #010a3d;
        padding: 0;
        margin: 0;
        width: 100%;
        height: 100%;
        --scale: 1;
    }
    
    .homepage {
        width: 1920px;
        height: 1080px;
        background: rgb(101, 154, 252);
        background-size: 100% 100%;
        position: absolute;
        transform: scale(var(--scale)) translate(-50%, -50%);
        transform-origin: 0 0;
        left: 50%;
        top: 50%;
        transition: 0.3s;
    }
<!--自动缩放容器 1920*1080 -->
<div id="homepage" v-cloak class="ScaleBox" ref="ScaleBox" :style="{width: width + 'px',height: height + 'px'}">

<script>
    'use strict';
    var homepage = new Vue({
        el: '#homepage',
        data() {
            return {
                scale: 0,
                width: 1920,
                height: 1080,
            }
        },
        mounted() {
            //以1920*1080设计稿 为标准尺寸进行自动缩放
            this.setScale();
            window.addEventListener("resize", this.debounce(this.setScale));
      
        },
        methods: {
            getScale() {
                // 固定好16:9的宽高比,计算出最合适的缩放比
                const {width, height} = this;
                const wh = window.innerHeight / height;
                const ww = window.innerWidth / width;
                console.log(ww < wh ? ww : wh);
                return ww < wh ? ww : wh;
            },
            setScale() {
                // 获取到缩放比例,设置它
                this.scale = this.getScale();
                if (this.$refs.ScaleBox) {
                    this.$refs.ScaleBox.style.setProperty("--scale", this.scale);
                }
            },
            debounce(fn, delay) {
                const delays = delay || 500;
                let timer;
                return function () {
                    const th = this;
                    const args = arguments;
                    if (timer) {
                        clearTimeout(timer);
                    }
                    timer = setTimeout(function () {
                        timer = null;
                        fn.apply(th, args);
                    }, delays);
                };
            },
        },
        created() {
        }
    })
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值