现在大屏适配插件有很多PostCss,vue2-scale-box等。大多数都是基于rem方案和scale方案,今天来做一个总结。
1.rem方案
思路:设置 rem 的基准值 ,动态的计算html根元素的font-size
缺点:无法适配echarts图表字体需要单独做处理
2.translate方案,推荐
思路:基于css3属性transform进行实现,根据设计稿的宽高比,对最外层元素进行等比例缩小或放大,里面元素也跟随变化
缺点:一些屏幕宽高比和设计稿的宽高比不一致时会出现俩边留白
// 配置项
const init = {
DOM: '#app', // dom元素
baseWidth: 1920, //设计稿尺寸(px)
baseHeight: 1080, //设计稿尺寸(px)
// 默认缩放值
scale: {
width: '1',
height: '1',
}
}
// * 定时函数
let drawTiming = null
const {DOM, baseWidth, baseHeight, scale} = init
function calcRate () {
const appRef = document.querySelector(DOM)
// * 需保持的比例(默认1.77778)
const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))
if (!appRef) return
// 当前宽高比
const currentRate = parseFloat((window.innerWidth / window.innerHeight).toFixed(5))
if (appRef) {
if (currentRate > baseProportion) {
// 表示更宽
scale.width = ((window.innerHeight * baseProportion) / baseWidth).toFixed(5)
scale.height = (window.innerHeight / baseHeight).toFixed(5)
appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
} else {
// 表示更高
scale.height = ((window.innerWidth / baseProportion) / baseHeight).toFixed(5)
scale.width = (window.innerWidth / baseWidth).toFixed(5)
appRef.style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
}
}
}
function resize () {
clearTimeout(drawTiming)
drawTiming = setTimeout(() => {
calcRate()
}, 200)
}
// 开启计算
export function startResize(){
calcRate()
window.addEventListener('resize', resize)
}
// 移除监听
export function removeResize(){
window.removeEventListener('resize', resize)
}