1、引入包
npm install postcss-px2rem
2、配置postcss.config.js
module.exports = {
plugins: {
'postcss-px2rem': {
remUnit: 46.875
}
}
}
3、在html文件增加脚本动态修改fontsize
<script>
; (function (win, doc) {
var docEl = doc.documentElement,
UA = navigator.userAgent;
var refreshRem = function () {
var w = docEl.getBoundingClientRect().width || 320;
var fontSize = w / 320 * 20;
fontSize = fontSize > 40 ? 40 : fontSize;
docEl.style.fontSize = fontSize + 'px';
var finalFontSize = parseFloat(win.getComputedStyle(docEl).getPropertyValue("font-size"));
if (finalFontSize === fontSize) return;
fontSize = fontSize + (fontSize - finalFontSize);
docEl.style.fontSize = fontSize + 'px';
win.fontSize = fontSize;
}, refreshRemId;
win.addEventListener('resize', function () {
clearTimeout(refreshRemId);
refreshRemId = setTimeout(refreshRem, 100);
}, false);
win.addEventListener('pageshow', function (e) {
if (e.persisted) {
clearTimeout(refreshRemId);
refreshRemId = setTimeout(refreshRem, 100);
}
}, false);
refreshRem();
})(window, document);
</script>
以上配置对应750px设计稿(用过remUnit是其他值的,试了不太行~)
module.exports = {
plugins: {
autoprefixer: {},
'postcss-px2rem':{
remUnit: 75
}
}
}
index.html
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<script>
(function (doc, win) {
const docEl = doc.documentElement;
const resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize';
const recalc = function () {
const clientWidth = docEl.clientWidth > 750 ? 750 : docEl.clientWidth;
if (!clientWidth) return;
docEl.style.fontSize = clientWidth / 10 + 'px';
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
</script>
版权声明:本文为Cookysurongbin原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。