/* # 按照宽高比例设定html字体, width=device-width initial-scale=1版 # @pargam win 窗口window对象 # @pargam option{ designwidth: 设计稿宽度,必须 designheight: 设计稿高度,不传的话则比例按照宽度来计算,可选 designfontsize: 设计稿宽高下用于计算的字体大小,默认20,可选 callback: 字体计算之后的回调函数,可选 } # ps:请尽量第一时间运行此js计算字体 */ !function(win, option) { var count = 0, designwidth = option.designwidth, designheight = option.designheight || 0, designfontsize = option.designfontsize || 100, callback = option.callback || null, root = document.documentelement, body = document.body, rootwidth, newsize, t, self; //返回root元素字体计算结果 function _getnewfontsize() { var iw=win.innerwidth>750?750:win.innerwidth; var scale = designheight !== 0 ? math.min(iw / designwidth, win.innerheight / designheight) : iw / designwidth; return parseint( scale * 10000 * designfontsize ) / 10000; } !function () { rootwidth = root.getboundingclientrect().width; self = self ? self : arguments.callee; //如果此时屏幕宽度不准确,就尝试再次获取分辨率,只尝试20次,否则使用win.innerwidth计算 if( rootwidth !== win.innerwidth && count < 20 ) { win.settimeout(function () { count++; self(); }, 0); } else { newsize = _getnewfontsize(); //如果css已经兼容当前分辨率就不管了 if( newsize + 'px' !== getcomputedstyle(root)['font-size'] ) { root.style.fontsize = newsize + "px"; return callback && callback(newsize); }; }; }(); //横竖屏切换的时候改变fontsize,根据需要选择使用 win.addeventlistener("onorientationchange" in window ? "orientationchange" : "resize", function() { cleartimeout(t); t = settimeout(function () { self(); }, 200); }, false); }(window, { designwidth:750 });