Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

针对部分Android机型的根px不等于设置的px,导致rem误差的解决方案 #97

Closed
fly-studio opened this issue Nov 24, 2016 · 3 comments

Comments

@fly-studio
Copy link

fly-studio commented Nov 24, 2016

比如华为的某款老机型,因为他们算法的问题,设置的fontSize,不等于最终编译得到的

var $html = $('html');
var html = document.getElementsByTagName('html')[0];

alert(html.style.fontSize);  // 36px 这说明 <html style="font-size:36px">
alert(window.getComputedStyle(html).fontSize); //31px
alert($html.css('font-size')); // 31px

根据实验,设置为42px的时候,华为会计算为36px

//这句话设置虽然可行,但是不知道什么原因会页面会闪一下,然后又还原回去
html.style.fontSize = '42px';
alert(window.getComputedStyle(html).fontSize); //36px

//jQuery的设置是有效的,并且页面不会闪回去
$html.attr('style', 'font-size:' + 42 + 'px!important;');
alert($html.css('font-size')); //36px

将上例改为,必须!important 才能让页面有效

html.setAttribute('style', 'font-size:42px!important'); //实验了html.style.fontSize = '42px!important' 都不行
@fly-studio fly-studio changed the title 针对部分Android机型的rem解决方案 针对部分Android机型的根px不等于设置的px,导致rem误差的解决方案 Nov 24, 2016
@fly-studio
Copy link
Author

fly-studio commented Nov 24, 2016

所以最终的设置JS代码为

var html = document.getElementsByTagName('html')[0];
var settedFs = settingFs = parseInt(html.style.fontSize); 
var whileCount = 0;
while(true) {
	var realFs = parseInt(window.getComputedStyle(html).fontSize);
	var delta = realFs - settedFs;
	if (Math.abs(delta) >= 1) //不相等
	{
		if (delta > 0) settingFs--; else settingFs++;
		html.setAttribute('style', 'font-size:'+settingFs + 'px!important');
	} else 
		break;
	if (whileCount++ > 100) //之所以弄个100的循环跳出的原因,在于实在无法预判设备是否能计算得到36px,比如设备只能计算35px,37px,这样会死循环只能跳出了
		break
}

设置循环100次跳出也是无奈之举,鬼晓得那个设备能不能设置到预定的值

@mingelz
Copy link
Contributor

mingelz commented Nov 24, 2016

看看是不是和 Font Boosting (amfe/article#10) 有关系

@airen airen closed this as completed Dec 6, 2016
@renyuns
Copy link

renyuns commented Mar 27, 2020

Android 实在是太坑爹了,各种厂商自己搞自己的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants