移动端rem方法适配方案,可直接使用,代码如下:
// 路径 js/rem.js
function remSize() {
let deviceWidth = document.documentElement.clientWidth || window.innerWidth
if ( deviceWidth >= 750 ) {
deviceWidth = 750
}
if ( deviceWidth <= 320 ) {
deviceWidth = 320
}
// 个人本地开发习惯使用375*667,此处375/7.5 = 50,设置1rem=50px
document.documentElement.style.fontSize = ( deviceWidth/7.5 ) + 'px'
document.querySelector('body').style.fontSize = 0.3 + 'rem'
}
remSize()
window.addEventListener('resize', function(){
remSize()
})
// 此处建议使用addEventListener,
// 下面方法若项目其他模块也在window上绑定onresize事件,会与其发生冲突
// window.onresize = function() {
// remSize()
// }
在vue中使用时,直接在其index.html中引入即可。
<script src="<%= BASE_URL %>js/rem.js"></script>