JS implements rem adaptation

1.rem definition

rem is a relative length unit. It is a css unit (adaptation unit rem) of the font-size value of the root element (html).

eg: When the font-size of the html tag is set to 16px on the page, 1rem = 16px

html{
    font-size:16px;//根元素字体大小,此时1rem = 16px
}

2. Dynamically set the html font size according to the width of different devices to realize the adaptation of rem under different devices

 eg: Take the computer 1920px design width as an example, set the font-size of the HTML root element according to the actual screen width, 1rem is equal to

rem = screen width/design draft width (1920px) *100

If the screen width is 1920px, that is, 1rem = 100px, if you need to set a div title size to 20px, width to 200px, and height to 100px, then

div{
    font-size:0.2rem,
    width:2rem,
    height:1rem
}

In this way, under different screens, the actual size of different DOM elements is  the screen width/1920 , achieving proportional scaling

rem adaptation code implementation:

(function(designWidth, maxWidth) {
	var doc = document,
		win = window,
		docEl = doc.documentElement,
		remStyle = document.createElement("style"),
		tid;

	function refreshRem() {
		var width = docEl.getBoundingClientRect().width;//屏幕宽度
		maxWidth = maxWidth || 540;//设置最大宽度
		width < 800  && (width = 800);//设置最小宽度
		width > maxWidth && (width = maxWidth);
		var rem = width * 100 / designWidth;//屏幕宽度 / 设计稿宽度 * 100,若为电脑运行,此时rem=100
		remStyle.innerHTML = 'html{font-size:' + rem + 'px;}'//此时重新定义html根元素大小为1rem,即100px
	}

	if (docEl.firstElementChild) {
		docEl.firstElementChild.appendChild(remStyle);
	} else {
		var wrap = doc.createElement("div");
		wrap.appendChild(remStyle);
		doc.write(wrap.innerHTML);
		wrap = null;
	}
	//要等 wiewport 设置好后才能执行 refreshRem,不然 refreshRem 会执行2次;
	refreshRem();

	win.addEventListener("resize", function() {
		clearTimeout(tid); //防止执行两次
		tid = setTimeout(refreshRem, 300);
	}, false);

	win.addEventListener("pageshow", function(e) {
		if (e.persisted) { // 浏览器后退的时候重新计算
			clearTimeout(tid);
			tid = setTimeout(refreshRem, 300);
		}
	}, false);

	if (doc.readyState === "complete") {
		doc.body.style.fontSize = "16px";
	} else {
		doc.addEventListener("DOMContentLoaded", function(e) {
			doc.body.style.fontSize = "16px";
		}, false);
	}
})(1920, maxWidth);//此处传入设计稿宽度及最大宽度

Put the code in the js file, call it on the page, or write it directly in the script tag of the index.html page.

Guess you like

Origin blog.csdn.net/dai556688/article/details/129667781