一、移动端需要处理1物理像素的原因
原因是像素比,在设置了完美视口之后,像素比=物理像素/设备独立像素=物理像素/CSS逻辑像素,从而推导出:物理像素=像素比*CSS逻辑像素;例如,DPR为2的iphone6S,设置高度为1px(CSS逻辑像素),所以占用的物理个数=2*1px=2px,即是说高度为1px的CSS像素在DPR为2的移动设备上,占用了2个物理像素。
二、initial-scale处理方式
按照第一点说到的情况,相当于像素比把CSS像素放大了DRP倍,既然是放大了CSS像素,反过来,我们可以通过initial-scale来进行缩小操作。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width,initial-scale=1.0"> 6 <title>1px物理像素</title> 7 <style media="screen"> 8 *{ 9 margin: 0; 10 padding: 0; 11 } 12 #div1{ 13 width: 16rem; 14 height: 1px; 15 margin-top: 3rem; 16 background: blue; 17 } 18 </style> 19 </head> 20 <body> 21 <div id="div1"></div> 22 <script> 23 (function(){ 24 let dpr = window.devicePixelRatio || 1; 25 let scale = 1 / dpr; 26 27 // rem 适配 28 let w = document.documentElement.clientWidth / 16 * dpr; 29 let styleNode = document.createElement(‘style‘); 30 styleNode.innerHTML = "html{font-size:" + w + "px !important;}" 31 document.head.appendChild(styleNode); 32 33 // 缩小操作 34 metaDOM = document.querySelector("meta[name=‘viewport‘]"); 35 metaDOM.content = "width=device-width,initial-scale=" + scale + ",user-scalable=no,minimum-scale=" + scale + ",maximum-scale=" + scale; 36 })(); 37 </script> 38 </body> 39 </html>
三、媒体查询&&transform处理方式
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width,initial-scale=1.0"> 6 <title>1px物理像素</title> 7 <style media="screen"> 8 *{ 9 margin: 0; 10 padding: 0; 11 } 12 #div1{ 13 width: 16rem; 14 height: 1px; 15 margin-top: 3rem; 16 background: blue; 17 } 18 @media only screen and (-webkit-device-pixel-ratio: 2){ 19 #div1{ 20 transform: scaleY(0.5); 21 } 22 } 23 @media only screen and (-webkit-device-pixel-ratio: 3){ 24 #div1{ 25 transform: scaleY(0.333333333); 26 } 27 } 28 </style> 29 </head> 30 <body> 31 <div id="div1"></div> 32 <script> 33 (function(){ 34 // rem 适配 35 let w = document.documentElement.clientWidth / 16; 36 let styleNode = document.createElement(‘style‘); 37 styleNode.innerHTML = "html{font-size:" + w + "px !important;}" 38 document.head.appendChild(styleNode); 39 })(); 40 </script> 41 </body> 42 </html>