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