问题引入及解决
最近做大屏项目,有一个现实问题:不同屏幕如何保证页面按 16:9 显示。
由于不同设备屏幕尺寸、分辨率不同,系统一般会对屏幕尺寸进行出乎意料的缩放,这大多数时候,会导致用户体验变差。有时还需要考虑横竖屏问题,为了使得web页面在不同移动设备上具有相适应的展示效果,必须在开发过程中使用合理的适配方案来解决这个问题。
rem 方案提供了较好的解决办法:
根据页面宽高比16:9,总是让页面宽/高等于设备宽/高偏小者。
- 当设备较宽时,设备宽高比 > 16/9,此时页面高度即为设备高度
- 当设备较高时,设备宽高比 <= 16/9,此时页面宽度就是设备宽度
因此,页面宽、高有如下计算方法:
其中,Wp 为页面有效宽度,Hp 为页面有效高度。
宽高设置准确了,再使页面左右居中,上下居中,四周留白即可。
然后,在 <head> 中设置字体按比例缩放 1rem = W / 100 ,即可达到效果。
代码实现
index.html
<head>
<script>
// 采用动态rem方案响应页面布局
const clientWidth = document.documentElement.clientWidth;
const clientHeight = document.documentElement.clientHeight;
const pageWidth = clientWidth / clientHeight > 16 / 9 ? clientHeight * 16 / 9 : clientWidth;
const pageHeight = pageWidth * 9 / 16;
// 设置 1rem = pageWidth/100
const string = `
<style>
html{
font-size: ${pageWidth / 100}px;
}
</style>
`;
// 将style标签写入页面
document.write(string);
</script>
</head>
<body>
<div id="root"></div>
<script>
// 设置root宽高
root.style.width = pageWidth + "px";
root.style.height = pageHeight + "px";
root.style.background = "pink";
// 设置root上下居中
root.style.marginTop = (clientHeight - pageHeight) / 2 + "px";
// 设置root左右居中(可以直接写在css中)
root.style.marginLeft = "auto";
root.style.marginRight = "auto";
</script>
</body>
使用 rem 代替 px
当使用宽高自适应响应式布局之后,就不能使用 px 单位将每个元素尺寸写死了,此时就需要用 rem 来计算元素的尺寸。
根据页面与设计稿的尺寸与宽度之比相等,可知:
因此,页面尺寸只需通过如下px函数就能计算得到:
@function px($n) {
@return $n / widthDesign * 100rem;
}
其中,$n 为设计稿实际尺寸;
常量 widthDesign 为设计稿实际宽度,由实际测量得到。