第一种方法
1.1引入js文件
(function (win) {
var doc = win.document;
var html = doc.documentElement;
var option = html.getAttribute('data-use-rem');
if (option === null) return; // defaut
var baseWidth = option === 'default' || option === '' || parseInt(option) <= 0 ? 750 : parseInt(option);
var grids = baseWidth / 100,
resizeEvt = 'orientationchange' in win ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = html.clientWidth || 320; // default to 320 if can't get device-width
html.style.fontSize = clientWidth / grids + 'px'; }; // Abort if browser does not support addEventListener
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false); recalc();})(window);
1.2.在index.html里面设置 data-use-rem 这样就可以了 不需要手动再设置基础字体
<html data-use-rem>~
第二种方法
2.1同样首先引入rem.js文件
// 监听屏幕滚动事件,
设置callback为改变字体大小事件window.addEventListener('resize', setHtmlFontSize)setHtmlFontSize();
/** @method setHtmlFontSize 改变根节点字体大小的函数 *
计算:当前屏幕 / 标准的750屏幕 * 标准屏幕根元素的字体大小 */function setHtmlFontSize() {
//1. 当前屏幕的宽度 var windowWidth = document.documentElement.offsetWidth;
// 限制最大屏幕和最小屏幕
if (windowWidth > 750) { windowWidth = 750; }
else if (windowWidth < 320) { windowWidth = 320; }
//2. 标准屏幕的宽度
var StandardWidth = 750;
// 标准屏幕的html的字体大小
var StandardHtmlFontSize = 100;
//3. 当前屏幕需要设置的根元素的字体大小
var htmlFontSize = windowWidth / StandardWidth * StandardHtmlFontSize;
//4. 把当前计算的html 字体大小设置到页面的html元素上就可以
document.querySelector('html').style.fontSize = htmlFontSize + 'px';}
2.2 切记 需要设置基础字体 根据自己需求
html{
font-size:100px;
}
body{
font-size:16px//这里是给未设置字体的标签设置的保留字体大小
}