使用js实现适配
html内的js
使用
Element.getBoundingClientRect().width
方法
兼容性比较好 IE5+支持
(function () {
var myhtml = document.documentElement;
var htmlWidth = myhtml.getBoundingClientRect().width;
myhtml.style.fontSize = htmlWidth / 15 + "px";
})()
可以直接使用一个自调用函数在js执行时根据当前视口宽度进行调节根节点字体大小,然后配合rem
完成适配
使用scss
- 首先抽离一个rem()方法
// 弹性设置,由px=>rem ,rem=>vw
// rem 单位换算:定为 75px 只是方便运算,750px-75px、640-64px、1080px-108px,如此类推
$vw_fontsize: 75; // iPhone 6尺寸的根元素大小基准值
// 根元素大小使用 vw 单位
$vw_design: 750;
@function rem($px) {
@return ($px / $vw_fontsize ) * 1rem;
}
- 配合设置html的根字体大小
// 抽离的rem方法文件
@import '~@styles/common';
html {
font-size: ($vw_fontsize / ($vw_design / 2)) * 100vw;
font-family: PingFangSC-Semibold;
@media screen and (max-width: 320px) {
font-size: 64px;
}
@media screen and (min-width: 540px) {
font-size: 108px;
}
}
body {
margin: 0 auto;
padding: 0;
max-width: 540px;
min-width: 320px;
background: #F5F5F5;
font-size: rem(32);
}
div{
box-sizing: border-box;
}
- 在需要使用rem方法的地方引入
@import '~@styles/common'
即可
使用less
// 设计稿宽度 和 设计稿上的基准值
@psdwidth: 640px;
@baseSize: 100px;
// 要兼容的设备
@deviceWidth: 320px, 360px, 375px, 384px, 411px, 414px, 480px, 549px,600px, 640px, 750px;
@deviceCount: length(@deviceWidth);
//使用遍历的方法,但是less不支持遍历,但是支持方法调用自己,即:递归
//但是也要加调用规则,符合某个条件调用||不符合某个条件终止
//使用when,当符合某个条件时调用
.adapter(@count) when (@count <= @deviceCount){
@media (min-width:extract(@deviceWidth,@count)) {
html{
//等比缩放的关键就是 其他视口宽度的基准值都和 (参考视口+参考基准值) 有关
font-size: extract(@deviceWidth,@count) / @psdWidth * @baseSize ;
}
}
.adapter(@count+1)
}
.adapter(1);