1:rem适配
(function(){ var styleNode = document.createElement("style"); var w = document.documentElement.clientWidth/16; styleNode.innerHTML = "html{font-size:"+w+"px!important}"; document.head.appendChild(styleNode); })()
2:viewport适配的原理
viewport适配方案中,每一个元素在不同设备上占据的css像素的个数是一样的。但是css像素和物理像素的比例是不一样的,等比的*/
/*viewport适配的优缺点:
优点:所量即所得
缺点:没有使用完美视口*/
(function(){ var targetW = 640; var scale = document.documentElement.clientWidth/targetW; var meta = document.querySelector("meta[name='viewport']"); meta.content="initial-scale="+scale+",minimum-scale="+scale+",maximum-scale="+scale+",user-scalable=no"; })()
3:练习1物理像素的实现 让1个CSS像素代表一个物理像素(利用像素比缩放,利用CSS3)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"/> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #test{ 16rem; height: 1px; margin-top: 1rem; background: black; } </style> </head> <body> <div id="test"></div> </body> <script type="text/javascript"> window.onload=function(){ (function(){ var dpr = window.devicePixelRatio||1; var styleNode = document.createElement("style"); var w = document.documentElement.clientWidth*dpr/16; styleNode.innerHTML="html{font-size:"+w+"px!important}"; document.head.appendChild(styleNode); var scale = 1/dpr; var meta = document.querySelector("meta[name='viewport']"); meta.content="width=device-width,initial-scale="+scale; })() } </script> </html> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"/> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #test{ 100%; height:1px ; margin-top: 50px; background: black; } @media only screen and (-webkit-device-pixel-ratio:2 ) { #test{ transform: scaleY(.5); } } @media only screen and (-webkit-device-pixel-ratio:3 ) { #test{ transform: scaleY(.333333333333333333); } } </style> </head> <body> <div id="test"></div> </body> </html>