<script>
/*
# 按照寬高比例設定html字體, width=device-width initial-scale=1版
# @pargam win 窗口window對象
# @pargam option{
designWidth: 設計稿寬度,必須
designHeight: 設計稿高度,不傳的話則比例按照寬度來計算,可選
注意點: 安卓下 html的font-size設置小於12px的值不起做用
注意點: 安卓下 html的font-size設置小於12px的值不起做用
注意點: 安卓下 html的font-size設置小於12px的值不起做用
designFontSize: 設計稿寬高下用於計算的字體大小,默認100,可選
callback: 字體計算以後的回調函數,可選
}
# return Boolean;
# ps:請儘可能第一時間運行此js計算字體
*/
!function (win, option) {
var count = 0,
designWidth = option.designWidth,
designHeight = option.designHeight || 0,
designFontSize = option.designFontSize || 20,
callback = option.callback || null,
root = document.documentElement,
body = document.body,
rootWidth, newSize, t, self;css
root.style.width = '100%';
//返回root元素字體計算結果
function _getNewFontSize() {
//var scale = designHeight !== 0 ? Math.min(win.innerWidth / designWidth, win.innerHeight / designHeight) : win.innerWidth / designWidth;
var scale = (window.innerWidth) / designWidth;
return parseInt(scale * 10000 * designFontSize) / 10000;
}html
!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();
}, 300);
}, false);
}(window, {
designWidth: 750,
// designHeight: 1136,
designFontSize: 100, //安卓下不能設置小於12px的字體 因此這個值要儘可能大些
callback: function (argument) {
//console.log("test")
}
});
</script>函數