Vue中自适应缩放
px自动转化为rem(使用pxtorem)
在写项目的时候经常会有因为屏幕尺寸不同导致的页面混乱,而px转化为rem可以让页面按照相同的比例进行缩放,使页面效果保持一致。
注意:该插件在行内样式中不生效!!!
- 下载第三方包
npm i amfe-flexible // 用于设置 rem 基准值
npm install postcss-pxtorem -D // 是一款 postcss 插件,用于将px单位转化为 rem
- 在main.js中引入 ‘amfe-flexible’
import 'amfe-flexible';
- 新建一个和src平级的.eslintrc.js文件,并进行配置
module.exports = {
// 配置要使用的 PostCSS 插件
plugins: {
autoprefixer: {
browsers: ['Android >= 4.0', 'iOS >= 7', 'ie >= 10'],//配置要兼容到的环境信息
},
'postcss-pxtorem': {
rootValue:16,//通常情况下,我们会将 rootValue 设置为设计稿中根元素的字体大小(例如,如果设计稿中根元素的字体大小是 16px,那么我们可以将 rootValue 设置为 16,这样 1rem 就等于 16px。)
propList: ['*'], //属性的选择器,*表示通用
selectorBlackList: [], //忽略的选择器
},
},
}
其他
但是因为此时项目要求(看下图),pxtorem已经不符合要求了
function setScale() {
let designWidth = 1920; //设计稿的宽度,根据实际项目调整
let designHeight = 1080; //设计稿的高度,根据实际项目调整
let dom = document.querySelector('.app');//获取页面的容器
//元素存在,则会根据当前屏幕尺寸计算缩放比例,并将缩放和尺寸样式应用到容器元素上
if (dom) {
//样式用于进行缩放变换
dom.style.transform = `scale(${document.documentElement.clientWidth / designWidth}, ${document.documentElement.clientHeight / designHeight})`;
// transformOrigin 样式用于设置缩放变换的原点,默认是中心点,这里设置为左上角。
dom.style.transformOrigin = 'left top';
// width 和 height 样式用于设置容器元素的固定宽度和高度,以保持设计稿的尺寸。
dom.style.width = '1920px';
dom.style.height = '1080px';
} else {
// 元素不存在,则延迟 500 毫秒后再次调用
setTimeout(() => {
setScale();
}, 500);
}
}
css中设置
// 也可以使用absolute
position: fixed;
完整代码
<template>
<div class="app">
<router-view />
</div>
</template>
<script>
export default {
name: "",
props: {},
components: {},
data() {
return {};
},
computed: {},
watch: {},
created() {},
methods: {},
mounted() {
window.onresize = () => {
return (() => {
this.$nextTick(() => {
setScale();
});
})();
};
function setScale() {
let designWidth = 1920; //设计稿的宽度,根据实际项目调整
let designHeight = 1080; //设计稿的高度,根据实际项目调整
let dom = document.querySelector(".app");
if (dom) {
dom.style.transform = `scale(${
document.documentElement.clientWidth / designWidth
}, ${document.documentElement.clientHeight / designHeight})`;
dom.style.transformOrigin = "left top";
dom.style.width = "1920px";
dom.style.height = "1080px";
} else {
setTimeout(() => {
setScale();
}, 500);
}
}
setScale();
},
};
</script>
<style scoped lang="less">
*{
padding: 0;
margin: 0;
}
.app {
background: linear-gradient(
to right,
#dec2a2,
#dfbbc9
); /* 从左到右渐变,颜色可以根据需要调整 */
background-size: 100% 100%;
position: fixed;
}
</style>