1.设置meta标签:
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
2.JS部分:
(function (window, doc) {
var docEl = document.documentElement
var dpr = window.devicePixelRatio || 1
var scale = 1 / dpr
var metaEl = document.querySelector('meta[name="viewport"]')
// var tid
docEl.setAttribute('data-dpr', dpr)
metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no')
function refreshRem () {
var rem = docEl.clientWidth / 10
console.log('userAgent' + window.navigator.userAgent)
if (window.navigator.userAgent.indexOf('Android') > -1) { // 如果不是安卓设备则输出IOS的样式逻辑
docEl.style.fontSize = rem + 'px'
} else if (window.navigator.userAgent.indexOf('iPhone') > -1) { //如果不是安卓和IOS的样则默认执行pc的样式逻辑
docEl.style.fontSize = rem + 'px'
} else {
docEl.style.fontSize = (rem > 68.1 ? 68.1 : rem) + 'px'
window.addEventListener('load', function () {
document.body.style.maxWidth = '664px'
document.body.style.position = 'absolute'
document.body.style.left = '50%'
document.body.style.marginLeft = '-332px'
// document.getElementById('html').style.height = document.body.offsetHeight + 'px'
})
}
}
refreshRem()
window.addEventListener('pageshow', function (e) {
if (e.persisted) {
refreshRem()
}
})
window.addEventListener('resize', refreshRem)
})(window, document)
3.CSS部分
/*移动端适配计算 start*/
$baseUIPx : 750px;
@function pxToRem($px) {
@return $px / ($baseUIPx / 10) * 1rem;
}
样式编写:
如果设计稿给我们的宽度是750px,其中一个标题是60px,
font-size: pxToRem(60px);
通过pxToRem转换有些繁琐,我们可以通过直接设置html根节点的font-size大小,然后通过rem去适配既可.
html{font-size:52.0833px}