参考大屏设计器网站的设计思路:
http://gcpaas.gccloud.com/bigScreen/bigscreen/preview?code=bigScreen_x1l3MlbPZq
- 设计思路:
1、首先大屏标准尺寸为1920px*1080px尺寸惊醒设计和开发
2、获取当前屏幕的宽高,计算出当前屏幕宽高分别缩放比,拿取缩放比更小的一组数据,作为整体根元素的缩放比例
const docEl = document.documentElement;
//获取到rem的基准值
const width = docEl.clientWidth;
const height = docEl.clientHeight;
const scale = width / 1920
const scale1 = height / 1080
const scales = scale > scale1 ? scale1 : scale
3、防抖监听页面的缩放,重新计算根元素的缩放比
window.addEventListener('resize', debounce(setRemUnit, 800))
防抖函数
function debounce (fn, ms) {
let timer = null
return () => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
fn();
}, ms);
};
}
4、通过transform中的scale属性对根元素进行缩放
appContainer.style=`transform:translate(-50%,-50%) scale(${scales});`
- 以下是完整代码(Vue3语法)
文件setScreenSize.js为完整的代码,并且在mian.js中引入即可完成屏幕自适应
import { nextTick } from 'vue'
export async function setRemUnit () {
console.log('计算根元素')
const docEl = document.documentElement;
//获取到rem的基准值
const width = docEl.clientWidth;
const height = docEl.clientHeight;
const scale = width / 1920
const scale1 = height / 1080
const scales = scale > scale1 ? scale1 : scale
await nextTick()
const appContainer = document.getElementById('appContainer')
appContainer.style = `transform:translate(-50%,-50%) scale(${ scales });`
}
setRemUnit()
//页面缩放防抖改变页面大小
window.addEventListener('resize', debounce(setRemUnit, 300))
function debounce (fn, ms) {
let timer = null
return () => {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
fn();
}, ms);
};
}