頁面樣式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相對單位即可!