Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

安卓webview相同rem值表现的不一样

两个安卓机AB

屏幕宽度都是360px

htmlfont-size都是36px

某个元素设置width: 2.64rem,

.item {
    width: 2.64rem
}

分别获取这个元素的宽度

alert($('.item').width())

最终A弹出的是95.0312px,B弹出的却是83.625px

这是为啥?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

自问自答了,这是问题也是答案

相对长度单位,相对于根元素(即html元素)font-size计算值的倍数

计算值,也就是说设置了font-size: 36px,但计算后单个后文字的宽度不一定是36px
在部分机型中会有误差,我这里设置36px,得到的却是31px,因此产生了这个问题。


解决方案:

1.首次设置到font-size后,计算真实宽度

function getTrueFontSize(){  
    var d = window.document.createElement('div');
    d.style.width = '1rem';
    d.style.display = "none";
    var head = window.document.getElementsByTagName('head')[0];
    head.appendChild(d);
    var trueFontSize = parseFloat(window.getComputedStyle(d,null).getPropertyValue('width'));
    return trueFontSize
}

2.更新font-size

//fontSize为第一次计算的font-size值
fontSize = fontSize * fontSize / getTrueFontSize();
docEl.style.fontSize = fontSize + 'px'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...