详解H5 活动页之移动端 REM 布局适配方法

2020-04-25 07:52:09易采站长站整理

var actualSize = win.getComputedStyle && parseFloat(win.getComputedStyle(docEl)["font-size"]);
if (actualSize !== rem && actualSize > 0 && Math.abs(actualSize - rem) > 1) {
var remScaled = rem * rem / actualSize;
docEl.style.fontSize = remScaled + 'px';
}
}
var timer;
//函数节流
function dbcRefresh() {
clearTimeout(timer);
timer = setTimeout(setFontSize, 100);
}
//窗口更新动态改变 font-size
WIN.addEventListener('resize', dbcRefresh, false);
//页面显示时计算一次
WIN.addEventListener('pageshow', function(e) {
if (e.persisted) {
dbcRefresh()
}
}, false);
setFontSize();
})(window)

另外,对于全屏显示的 H5 活动页,对宽高比例有所要求,此时应当做的调整。可以这么来做:


function adjustWarp(warpId = '#warp') {
// if (window.isMobile) return;
const $win = $(window);
const height = $win.height();
let width = $win.width();
// 考虑导航栏情况
if (width / height < 360 / 600) {
return;
}
width = Math.ceil(height * 360 / 640);
$(warpId).css({
height,
width,
postion: 'relative',
top: 0,
left: 'auto',
margin: '0 auto'
});
// 重新计算 rem
window.setFontSize(width);
}

按照这种缩放方法,几乎在任何设备上都可以实现等比缩放的精确布局。

2.2 元素大小取值方法

第二个问题是元素大小的取值。

以设计稿宽度 1080px 为例,我们将宽度分为 10 等份以便于换算,那么 1rem = 1080 / 10 = 108px 。其换算方法为:


const px2rem = function(px, rem = 108) {
let remVal = parseFloat(px) / rem;
if (typeof px === "string" && px.match(/px$/)) {
remVal += 'rem';
}

return remVal;
}

例如,设计稿中有一个图片大小为 460×210 ,相对页面位置 top: 321px; left: 70; 。按照如上换算方式,得到该元素最终的 css 样式应为:


.img_demo {
position: absolute;
background-size: cover;
background-image: url('demo.png');
top: 2.97222rem;
left: 0.64814rem;
width: 4.25926rem;
height: 1.94444rem;
}

2.3 rem 布局方案的开发方式

通过以上方法,rem 布局方案就得到了实现。但是手动计算 rem 的取值显然不现实。

通过 less/sass 预处理工具,我们只需要设置 mixins 方法,然后按照设计稿的实际大小来取值即可。以 less 为例,mixins 参考如下:


// px 转 rem
.px2rem(@px, @attr: 'width', @rem: 108rem) {
@{attr}: (@px / @rem);
}

.px2remTLWH(@top, @left, @width, @height, @rem: 108rem) {