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

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

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

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

template

<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

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

<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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值