移動web rem適配解決方案——flexible.js+rem(淘寶)
首先蛔添,項(xiàng)目設(shè)計(jì)稿尺寸為750px。
一夸溶、下載flexible.js:(它的原理是將當(dāng)前設(shè)備寬度劃分為10等份)
//安徽工業(yè)經(jīng)濟(jì)職業(yè)技術(shù)學(xué)院 web技術(shù)項(xiàng)目組-收集整理 2022-10-20
(function flexible (window, document) {
var docEl = document.documentElement
var dpr = window.devicePixelRatio || 1
// adjust body font size
function setBodyFontSize () {
if (document.body) {
document.body.style.fontSize = (12 * dpr) + 'px'
}
else {
document.addEventListener('DOMContentLoaded', setBodyFontSize)
}
}
setBodyFontSize();
// set 1rem = viewWidth / 10
function setRemUnit () {
var rem = docEl.clientWidth / 10
docEl.style.fontSize = rem + 'px'
}
setRemUnit()
// reset rem unit on page resize
window.addEventListener('resize', setRemUnit)
window.addEventListener('pageshow', function (e) {
if (e.persisted) {
setRemUnit()
}
})
// detect 0.5px supports
if (dpr >= 2) {
var fakeBody = document.createElement('body')
var testElement = document.createElement('div')
testElement.style.border = '.5px solid transparent'
fakeBody.appendChild(testElement)
docEl.appendChild(fakeBody)
if (testElement.offsetHeight === 1) {
docEl.classList.add('hairlines')
}
docEl.removeChild(fakeBody)
}
}(window, document))
二缝裁、設(shè)置meta標(biāo)簽
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
三足绅、引入flexible.js文件
<script src='js/flexible.js'></script>
四韩脑、針對移動web項(xiàng)目粹污,初始化樣式
/* 如果屏幕超過了750px壮吩,那么我們就就按照750px設(shè)計(jì)稿來走,不會讓頁面超過750px ,使用媒體查詢來設(shè)置*/
@media screen and (min- 750px) {
html {
font-size: 75px !important;
}
}
body {
min-width: 320px;
max-width: 750px;
/* flexible.js把設(shè)計(jì)稿750px進(jìn)行10等分鸭叙,所以html文字大小設(shè)置為75px(750px/ 10),頁面元素rem值:頁面元素的px值/ 75(750px/75)*/
width: 10rem;
margin: 0 auto;
}
六柄延、針對不同編譯器缀程,選用適合的插件,提升編譯效率滤奈。
VSCODE 中可使用插件:cssrem撩满,默認(rèn)的Root Font Size是16px,此時(shí)需要改為75px昭躺。
HBuilderX中可設(shè)置1rem對px轉(zhuǎn)換比例為75伪嫁。