移动端页面适配meta,自适应缩放大小
程序员文章站
2022-06-05 21:14:00
页面样式CSS代码使用rem或者em相对单位即可! ......
1 !function(win, lib) { 2 var timer, 3 doc = win.document, 4 docelem = doc.documentelement, 5 vpmeta = doc.queryselector('meta[name="viewport"]'), 6 dpr = 1, 7 scale = 1; 8 // 插入 viewport meta 9 if (!vpmeta) { 10 vpmeta = doc.createelement("meta"); 11 12 vpmeta.setattribute("name", "viewport"); 13 vpmeta.setattribute("content", 14 "width=device-width,initial-scale=" + scale + ", maximum-scale=" + scale + ", minimum-scale=" + scale + ", user-scalable=no"); 15 16 if (docelem.firstelementchild) { //在头部添加viewpoint 17 docelem.firstelementchild.appendchild(vpmeta) 18 } else { // 如果获取不到头部,就用创建元素然后写入发方法来写入到页面里 19 var div = doc.createelement("div"); 20 div.appendchild(vpmeta); 21 doc.write(div.innerhtml); 22 } 23 } 24 function setfontsize() { 25 var winwidth = docelem.getboundingclientrect().width; 26 if(winwidth>750){winwidth=750} //限制最大宽度 27 // 根节点 fontsize 根据宽度决定(到时候算rem的时候,就用设计稿宽度/) 28 var basesize = winwidth / 10; 29 docelem.style.fontsize = basesize + "px"; 30 } 31 // 调整窗口时重置 32 win.addeventlistener("resize", function() { 33 cleartimeout(timer); 34 timer = settimeout(setfontsize, 300); 35 }, false); 36 // orientationchange 时也需要重算下吧(翻转设备) 37 win.addeventlistener("orientationchange", function() { 38 cleartimeout(timer); 39 timer = settimeout(setfontsize, 300); 40 }, false); 41 // pageshow 42 // keyword: 倒退 缓存相关 43 win.addeventlistener("pageshow", function(e) { 44 if (e.persisted) { 45 cleartimeout(timer); 46 timer = settimeout(setfontsize, 300); 47 } 48 }, false); 49 // 设置基准字体 50 if ("complete" === doc.readystate) { 51 doc.body.style.fontsize = 24/75 + "rem"; 52 } else { 53 doc.addeventlistener("domcontentloaded", function() { 54 doc.body.style.fontsize = 24/75 + "rem"; 55 }, false); 56 } 57 setfontsize(); 58 }(window, window.lib || (window.lib = {}));
页面样式css代码使用rem或者em相对单位即可!