vue3 自适应代码,可按屏幕大小自动进行缩放

完整程序,已上传。

核心代码:

// 实际观察的元素
var actrulEle = null;

const scale = {
    width: "1",
    height: "1",
};

// * 设计稿尺寸(px)
const baseWidth = 1920;
const baseHeight = 1080;

// * 需保持的比例(默认1.77778)
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5));

/* 
 * @param { HTMLElement } watchEl 等待观察的外部元素
 * @param { HTMLElement } el 实际需要响应外部元素改变而改变大小的内部元素
 * @param { Boolean } 确认是否进行或者取消监听
*/
const useWatchElement = (watchEl, el, watchFlag = true) => {
    actrulEle = el;
    if (ob && !el && !watchFlag) {
        ob.unobserve(watchEl);
        return false;
    }
    ob.observe(watchEl);
};

const calcRate = (el) => {
    const appRef = actrulEle;
    if (!appRef) return;
    // 获取待监听屏幕的长宽
    const width = window.innerWidth;
    const height = window.innerHeight;
    // 当前宽高比
    const currentRate = parseFloat((width / height).toFixed(5));
    // console.log(width, height);
    if (width != 0 && height != 0) {
        if (currentRate > baseProportion) {
            // 表示比基准宽高更宽
            scale.width = ((height * baseProportion) / baseWidth).toFixed(5);
            scale.height = (height / baseHeight).toFixed(5);
            appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
        } else {
            // 表示比基准宽高更高
            scale.height = (width / baseProportion / baseHeight).toFixed(5);
            scale.width = (width / baseWidth).toFixed(5);
            appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`;
        }
    } else {
        return false;
    }
};

let ids = null

// const ob = new ResizeObserver((e) => {
//     const target = e[0].target;
//     if (target.offsetWidth != 0 && target.offsetHeight != 0) {
//         if (ids) {
//             window.cancelAnimationFrame(ids)
//         }
//         if (target.offsetWidth < 300) { // 原来是600,现在改成400,因为如果改成600网页放大到500%的时候,内容还是会变大。现在固定不变了---wxc    2023-01-06
//             // 宽度小于 600 的时候取消适配,大于等于 600 重新适配
//             window.cancelAnimationFrame(ids)
//             ids = null
//             return false;
//         }
//         ids = window.requestAnimationFrame(() => calcRate(target))
//     }
// });
let resizeTimer;
const debounceDelay = 100; // 适当延迟时间

const ob = new ResizeObserver((e) => {
    const target = e[0].target;
    if (target.offsetWidth === 0 || target.offsetHeight === 0) return;
    
    if (target.offsetWidth < 300) { // 原来是600,现在改成400,因为如果改成600网页放大到500%的时候,内容还是会变大。现在固定不变了---wxc    2023-01-06
        if (ids) {
            window.cancelAnimationFrame(ids);
            ids = null;
        }
        return;
    }
    
    // 清除之前的定时器
    if (resizeTimer) {
        clearTimeout(resizeTimer);
    }
    
    // 设置新的定时器
    resizeTimer = setTimeout(() => {
        if (ids) {
            window.cancelAnimationFrame(ids);
        }
        ids = window.requestAnimationFrame(() => calcRate(target));
    }, debounceDelay);
});

export default useWatchElement;

Vue3中,可以通过监听窗口大小变化事件,动态计算需要缩放的比例,从而实现根据屏幕大小自适应宽高缩放的效果。具体实现方法可以参考以下代码: ```html <template> <div :style="{transform: `scale(${scaleRatio})`}"> <!-- 需要自适应缩放的内容 --> </div> </template> <script> import { reactive, onMounted, onUnmounted } from &#39;vue&#39; export default { setup () { const state = reactive({ scaleRatio: 1 // 默认缩放比例为1 }) // 监听窗口大小变化事件 const onResize = () => { const { innerWidth, innerHeight } = window const screenWidth = 1920 // 设计稿的宽度 const screenHeight = 1080 // 设计稿的高度 const scaleX = innerWidth / screenWidth const scaleY = innerHeight / screenHeight state.scaleRatio = scaleX > scaleY ? scaleY : scaleX // 取较小的缩放比例 } onMounted(() => { window.addEventListener(&#39;resize&#39;, onResize) }) onUnmounted(() => { window.removeEventListener(&#39;resize&#39;, onResize) }) return state } } </script> ``` 在上面的代码中,我们使用了Vue3中的reactive函数创建了一个响应式对象state,用来保存当前的缩放比例。在setup函数中,我们使用onMounted和onUnmounted函数分别在组件挂载和卸载时监听和移除窗口大小变化事件。在事件处理函数onResize中,我们根据窗口大小和设计稿的宽高计算出需要缩放的比例,并将其保存到state对象中。在模板中,我们使用:style绑定将缩放比例应用到需要自适应缩放的内容上,实现根据屏幕大小自适应宽高缩放的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值