scss使用自定义函数实现单位像素随屏幕比例动态缩放

vue中通过变量和scss函数来动态实现动态缩放像素

简单来说就是比例缩小时,像素单位变大,从而字体大小相对不变,以下仅处理比例缩小的状况

自定义一个属性--size,初始值为1px

template

html 复制代码
<template>
  <div class="home" style="--size:1px">
    hello world!
  </div>
</template>

map为:{100: 1, 90: 1.1, 80: 1.2, 75: 1.3, 67: 1.5, 50: 2, 33: 3, 25: 4 }

  • 屏幕100%时,size=1 => mpx(1) => 1px
  • 屏幕90%时,size=1.1 => mpx(1) => 1.1px
  • ......

js

javascript 复制代码
export default {
  name: "Index",
  data() {
    return {
      // 屏幕缩放比例对应的zoom值
      map = {100: 1, 90: 1.1, 80: 1.2, 75: 1.3, 67: 1.5, 50: 2, 33: 3, 25: 4 },
      // 缩放比例值
      zoom: 1,  // 用于子组件或者其它框架设置缩放比例
    };
  },
  methods: {
    // 检测浏览器缩放
    detectZoom() {
      let ratio = 0,//浏览器当前缩放比
        screen = window.screen,//获取屏幕
        ua = navigator.userAgent.toLowerCase();//判断登陆端是pc还是手机

      if (window.devicePixelRatio !== undefined) {
        ratio = window.devicePixelRatio;
      }
      else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
          ratio = screen.deviceXDPI / screen.logicalXDPI;
        }
      }
      else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
      }

      if (ratio) {
        ratio = Math.round(ratio * 100);
      }
      return ratio
    },

    // 屏幕变化,计算css的size变量
    calcSize() {
      let map = { 100: 1, 90: 1.1, 80: 1.2, 75: 1.3, 67: 1.5, 50: 2, 33: 3, 25: 4 }
      let ratio = this.detectZoom();
      let size = map[ratio] || 1;
      this.zoom = size;
      // 重设--size属性的值
      document.querySelector('.home').style.cssText = `--size: ${size}px`
      // document.getElementsByClassName('home')[0].style.setProperty("--size", size + "px");
    }
  },
  mounted() {
    this.calcSize();
    window.addEventListener('resize', () => {
      // 首页才响应
      if (this.$route.name == 'Index') {
        this.calcSize();
      }
    });
  }
}

calcSize()中重设了--size的值后,触发函数,在函数在使用calc()计算最新的值,从而实现缩放控制。

scss

css 复制代码
<style scoped lang="scss">
// 在scss中使用函数
@function mpx($size: 1) {
  @return calc(#{$size} * var(--size))	// 入参$size=10, 当属性--size=1.1px时 return 11px
}

.home{
  font-size: mpx(10); // --size=1时,font-size=10; --size=1.1时,font-size=11	单位根据--size来变换
}
</style>

css中最关键的是使用var()来定义一个属性,然后在js中修改这个属性的值

https://blog.csdn.net/weixin_45977607/article/details/122473489

https://juejin.cn/post/7070762204286435359

相关推荐
幽络源小助理1 小时前
SpringBoot+Vue攀枝花水果在线销售系统源码 | Java项目免费下载 – 幽络源
java·vue.js·spring boot
小肥宅仙女1 小时前
限流方案
前端·后端
雲墨款哥1 小时前
从一行好奇的代码说起:Vue怎么没有React的props.children
前端·vue.js·react.js
计算机学姐1 小时前
基于SpringBoot的演出购票系统【2026最新】
java·vue.js·spring boot·后端·spring·tomcat·intellij-idea
用户6802659051191 小时前
2025年十大终端管理软件推荐指南
vue.js·后端·面试
孜孜不倦不忘初心1 小时前
Axios 常用配置及使用
前端·axios
sTone873751 小时前
vscode 二开踩坑记录
前端
用户8168694747251 小时前
Effect 执行时机与事件循环交错关系
前端·react.js
心在飞扬1 小时前
langchain学习总结-OutputParser组件及使用技巧
前端·后端
llq_3501 小时前
Ant Design v5 样式兼容性问题与解决方案
前端