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

相关推荐
object not found10 小时前
基于uniapp开发小程序自定义顶部导航栏状态栏标题栏
前端·javascript·小程序·uni-app
Irene199110 小时前
v-model 在 Vue2 和 Vue3 中的实现对比或异同
vue.js
We་ct10 小时前
LeetCode 28. 找出字符串中第一个匹配项的下标:两种实现与深度解析
前端·算法·leetcode·typescript
xzl0410 小时前
小智服务端chat入口工具调用流程
java·服务器·前端
小码吃趴菜10 小时前
Shell脚本编程
前端·chrome
心.c10 小时前
Vue3+Node.js实现文件上传并发控制与安全防线 进阶篇
前端·javascript·vue.js·安全·node.js
pas13611 小时前
36-mini-vue nextTick
前端·javascript·vue.js
VX:Fegn089511 小时前
计算机毕业设计|基于springboot + vue教务管理系统(源码+数据库+文档)
vue.js·spring boot·课程设计
梅梅绵绵冰11 小时前
springboot初步1
java·前端·spring boot
星辰_mya11 小时前
nginx之待续-没写完
前端