介绍两种移动端适配方案
1. rem为主
-
设置根节点字体大小,页面元素都使用scss表达式将px转换为rem
// 在scss中 $mainSize:20px; html{font-size:$mainSize;} @function f($px){ @return $px/$mainSize/2*1rem; }
-
-
在页面进行缩放时更新根节点字体大小(设计稿640)
$(window).ready(function(){ $('html').css({'font-size': $(window).width() / 320 *20}); }); $(window).resize(function(){ $('html').css({'font-size': $(window).width() / 320 *20}); });
2. 通过js计算缩放比例控制适配(transform: scale(scale);),页面上最外层元素加上类名adapt
var adapt= { styleRule: { add: function(a, b) { var c = document.styleSheets[document.styleSheets.length - 1]; c.cssRules ? c.insertRule(a + "{" + b + "}", c.cssRules.length) : c.addRule(a, b) }, remove: function(a) { for (var b = 0; b < document.styleSheets.length; b++) { var c = document.styleSheets[b]; c.cssRules ? function() { for (var b = 0; b < c.cssRules.length; b++) c.cssRules[b].selectorText == a && c.deleteRule(b) }() : c.removeRule(a) } } }, reset: function() { adapt.styleRule.remove(".adapt") }, render: function(a) { function b() { adapt.scale = e / 320; adapt.styleRule.add(c, d.replace("{scale}", adapt.scale)); } var c, d = "-webkit-transform:scale({scale});-webkit-transform-origin:0px 0px 0px;margin:0px;width:320px;"; document.querySelectorAll(".adapt")[0] ? (c = ".adapt", d += "overflow:hidden;") : (console.warn(".adapt is undefined, open the default settings"), c = "body"); var e = window.innerWidth; document.body.clientWidth <= window.innerWidth && (e = document.body.clientWidth), a ? setTimeout(function() { b() }, 110) : b(); }, init: function() { var a = "onorientationchange" in window ? "orientationchange": "resize"; window.addEventListener(a, function() { adapt.render() }); } }; adapt.init(); adapt.render();
3. 自执行方法
(function(win,doc){ change(); function change(){ doc.documentElement.style.fontSize = doc.documentElement.clientWidth *20/375+'px'; } win.addEventListener('resize',change,false); win.addEventListener('orientationchange',change,false); })(window,document);
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/7517.html