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

相关推荐
剪刀石头布啊4 小时前
vue-react为何要虚拟dom
前端
剪刀石头布啊4 小时前
ahooks常用的一些库,我们使用一下
前端
剪刀石头布啊4 小时前
从git更新本地提交记录到更新已经推送到远端记录
前端
Flynt6 小时前
axios 被投毒半年后,我把 npm 的"安全防线"实测了一遍:最信任的 SHA512 是安慰剂
前端·npm·node.js
excel7 小时前
Base62 和 Base64 有什么区别?
前端
风骏时光牛马8 小时前
大模型底层架构与AI源码深度剖析
前端
掘金挖土9 小时前
前端手摸手跑路之 AI 应用开发(九)
前端·后端
中文呀11 小时前
三维 GIS 离线缓存实战:逆向 CesiumOfflineCache,并亲手为它补上"自动更新"能力
前端
前进前进前进12 小时前
TRAE 全链路实战:做了一个警示牌一键生成器:纯 Canvas、单文件、零依赖
前端