传统的方式
因为传统的方式都很熟悉,我就不写了,主要是改进版和最终版的写法
改进版
html&css
1 2 3 4 5 6
| <style> .box { background-color:pink; } </style> <div class="box"></div>
|
Js
1 2 3 4 5 6 7 8 9 10 11 12 13
|
var designWidth = 640, rem2px = 32; document.documentElement.style.fontSize = ((window.innerWidth / designWidth) * rem2px) + 'px';
var box = document.querySelector('.box'); console.log( box ) box.style.width = '1rem'; box.style.height = '1rem'
|
最终版
html&css
1 2 3 4 5 6
| <style> .box { background-color: pink; } </style> <div class="box"></div>
|
Js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
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 fontSize = adapt( 640, 32 ), box = document.querySelector('.box'); box.style.cssText = 'width:1rem;height:1rem'; console.log( fontSize );
|
最终结果
