Created
January 11, 2016 06:25
-
-
Save xiajngsi/dcd29ca13987d7fbf1f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by candice on 15/12/23. | |
*/ | |
var dpr, rem, scale; | |
var docEl = document.documentElement; | |
var fontEl = document.createElement('style'); | |
var metaEl = document.querySelector('meta[name="viewport"]'); | |
dpr = window.devicePixelRatio || 1; | |
if(docEl.clientWidth <= 768) { | |
rem = docEl.clientWidth * dpr / 40; | |
scale = 1 / dpr; | |
} else { | |
rem = 768 * dpr / 40; | |
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment