移动适配方案的总结

  1. js代码实现适配 
var dpr, rem, scale;
var docEl = document.documentElement;
var fontEl = document.createElement('style');
var metaEl = document.querySelector('meta[name="viewport"]');
//iphone6下font-size=20px
dpr = window.devicePixelRatio || 1;
rem = docEl.clientWidth * dpr / 37.5;  
scale = 1 / dpr;


// 设置viewport,进行缩放,达到高清效果
metaEl.setAttribute('content', 'width=' + dpr * docEl.clientWidth + ',initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale + ',user-scalable=no');

// 设置data-dpr属性,留作的css hack之用
docEl.setAttribute('data-dpr', dpr);

// 动态写入样式
docEl.firstElementChild.appendChild(fontEl);
fontEl.innerHTML = 'html{font-size:' + rem + 'px!important;}';

// 给js调用的,某一dpr下rem和px之间的转换函数
window.rem2px = function(v) {
    v = parseFloat(v);
    return v * rem;
};

window.px2rem = function(v) {
    v = parseFloat(v);
    return v / rem;
};

window.dpr = dpr;
window.rem = rem;

  2.媒体查询实现适配

html {
font-size : 20px;
 }
 @media only screen and (min-width: 401px){
 html {
 font-size: 25px !important;
 }
 }
 @media only screen and (min-width: 428px){
 html {
 font-size: 26.75px !important;
 }
 }
 @media only screen and (min-width: 481px){
 html {
 font-size: 30px !important; 
 }
 }
 @media only screen and (min-width: 569px){
 html {
 font-size: 35px !important; 
 }
 }
 @media only screen and (min-width: 641px){
 html {
 font-size: 40px !important; 
 }
 }

 

posted @ 2017-03-29 15:03  goweb  阅读(218)  评论(0编辑  收藏  举报