问题描述
在PC端项目中遇到元素过大或者内容过多时,不能在一个屏幕中显示,比如展示图表等看板项目需要一屏显示但是此时内容太多超出一屏高度,或者不同屏幕比例下可能超过一屏的高度。
解决方案
- 宽度设置百分比,外层高度给一个固定高度,里面区块元素高度也设置百分比,此种方案肯能会出现元素比例失调问题。
- 采用rem+媒体查询布局,此种方案不适合局部适配
- 对视口meta进行缩放,此种方案也不适合局部的适配
- 采用css缩放transform或者zoom,此种方案适合局部的适配,但是要对元素横纵缩放才能使其比例正常,可能会出现宽度不能撑满屏幕宽度问题
使用css transform动态缩放
- 为元素使用:style绑定缩放样式
<div :style={transform:`scale(${num})`}>
......
</div>
- 监听屏幕缩放比例设置合适的缩放值为浏览器的缩放添加监听事件
mounted(){
window.addEventListener("resize", ()=> {
this.detectZoom();
})
}
定义获取屏幕缩放比例函数
detectZoom() {
let ratio = 0
const screen = window.screen
const ua = navigator.userAgent.toLowerCase()
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
}
页面销毁前移除浏览器缩放的监听事件
beforeDestroy() {
window.removeEventListener('resize', this.detectZoom())
}
注意改方案在元素内容过多时有副作用可能会造成元素比例失调,因此设计图需要合理设计一屏显示的元素