js部分代码,先引入jq,window_width是设计稿的宽度,这时的换算比例是100px=1rem;
var window_width = 750;//设计稿的宽为750px时
var window_size = 100;
(function () {
$.fn.autoSize = function (options) {
options = $.extend({}, $.fn.autoSize.defaults, options || {});
autoSet();
$(window).resize(function () {
autoSet();
});
function autoSet() {
var width = $(this).width();
var newsize = $.fn.autoSize.method.getFS(options.designWith, options.designFS, width);
$.fn.autoSize.method.setFS(options.target, newsize);
}
};
$.fn.autoSize.method = {
getFS: function (designWith, designFs, winWith) {
return winWith / designWith * 100;
},
setFS: function (target, FS) {
target.style.fontSize = FS + "px";
}
};
$.fn.autoSize.defaults = {
designWith: window_width,
designFS: window_size,
target: document.documentElement
};
})(jQuery);
$(window).autoSize({
designWidth: window_width,
designFS: window_size
});
em换算是根据父元素的font-size变化的,浏览器的默认font-size为16px,此时,如果你将其子元素的字体大小设置为18px,就可以这样转成em值
1÷16×18=1.125em(1 ÷ 父元素的font-size × 需要转换的像素值 = em值)