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

淘宝 flexible.js 漏洞修补:记一次 rem 踩坑记录 #11

Open
Liqihan opened this issue Dec 29, 2017 · 0 comments
Open

淘宝 flexible.js 漏洞修补:记一次 rem 踩坑记录 #11

Liqihan opened this issue Dec 29, 2017 · 0 comments

Comments

@Liqihan
Copy link
Owner

Liqihan commented Dec 29, 2017

取这样的标题可能会被打,可是我确实顺带解决了淘宝flexible.js的问题。

先声明两个变量供下文使用:

//html style font-size

docElementFontSize= document.documentElement.style.fontSize;

//html 最终的 font-size

finalDocElementFontSize= window.getComputedStyle(window.document.documentElement).getPropertyValue("font-size")

rem是根据html的最终font-size进行响应: 1rem === finalDocElementFontSize(重点!) 。对于大部分机型,docElementFontSize和finalDocElementFontSize是相等的,但是有些网页在某些情况下打开的话,会得到docElementFontSize和finalDocElementFontSize不相等的情况,比如我公司的小米Max和荣耀8机型,在市场上算是比较新的机型,测试数据都是在QQ上演示,公司的土豪APP也会有这种情况。如下图:

小米Max

这是在小米Max的QQ开的测试页面 ,大佬可以扒网页看js,屏幕宽度是393px,html的style.fontSize是39.3px(页面宽度分成10等分),然而html最终fontSize是45.195px!!!下面设置一个灰色的box,高度是1rem,得到的样式高度是45.1875px!!!看到这很毁三观有木有。我在百度和谷歌没有查到关于这个的任何问题和资料。众所周知淘宝玩rem玩的飞起,用QQ打开m.taobao.com如下图:

小米Max 淘宝

淘宝在body写了overflow:hidden;width:100%;所以页面宽度超出部分隐藏了,再结合我测试的第一张图,页面宽度是393px,1rem=45.1875px,那10rem就超出了页面宽度。事实确实如此,如果设置页面宽度10rem,页面会出现横向滚动条。

解决方法也很简单,因为这类异常手机html的style.fontSize、html最终的fontSize和页面元素1rem的值都不相等,但是1rem和html的最终fontSize很接近。代码如下

/*

* 适用于获取屏幕宽度等分设置html的font-size情况,比如 flexible.js库

*/

//计算最终html font-size

functionmodifileRootRem(){

varroot= window.document.documentElement;

varfontSize= parseFloat(root.style.fontSize);

varfinalFontSize= parseFloat(window.getComputedStyle(root).getPropertyValue("font-size"));

if(finalFontSize=== fontSize)return;

root.style.fontSize= fontSize+(fontSize-finalFontSize)+ "px";

}

if(typeofwindow.=== 'function'){

varoldFun= window.;

window.= function(){

oldFun();

modifileRootRem();

}

}else{

window.= modifileRootRem;

}

通过docElementFontSize+(docElementFontSize – finalDocElementFontSize) 得到html.fontSize的值。适用这类特异机型的html.fontSize!

这个问题我特意问了下大漠老师,大佬只是说进行“特定”处理,看淘宝首页的情况也没做好很好的兼容,不出意外,我这是针对这类机型rem布局兼容的首创代码!

如有疑问欢迎评论讨论

觉得本文对你有帮助?请分享给更多人

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

No branches or pull requests

1 participant