失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 个人收藏的移动端网页布局rem解决方案

个人收藏的移动端网页布局rem解决方案

时间:2022-08-18 18:40:28

相关推荐

个人收藏的移动端网页布局rem解决方案

写移动端项目时,总是会纠结是用css3 media query 还是用rem。移动端框架挺多,但是因为项目都比较小,不考虑使用。

无意在网上找到一个移动端rem布局的解决方案,经个人实践,目前未出现什么大问题,收藏备用。

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>移动端rem布局</title><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" /><style>.test{width: 1rem;height: 1rem;background-color: #fa5275;}</style></head><body><div class="test"></div><p>设置前html的fontsize:16px;</p><p>设置前html的fontsize:16px;</p><script>function adapt(designWidth, rem2px){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 defaultFontSize = parseFloat(window.getComputedStyle(d, null).getPropertyValue('width'));d.remove();document.documentElement.style.fontSize = window.innerWidth / designWidth * rem2px / defaultFontSize * 100 + '%';var st = document.createElement('style');var portrait = "@media screen and (min-width: "+window.innerWidth+"px) {html{font-size:"+ ((window.innerWidth/(designWidth/rem2px)/defaultFontSize)*100) +"%;}}";var landscape = "@media screen and (min-width: "+window.innerHeight+"px) {html{font-size:"+ ((window.innerHeight/(designWidth/rem2px)/defaultFontSize)*100) +"%;}}" st.innerHTML = portrait + landscape;head.appendChild(st);return defaultFontSize;}var defaultFontSize = adapt(640, 100);</script></body></html>

如果觉得《个人收藏的移动端网页布局rem解决方案》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。