移动端完美适配方案

前言

  • 话不多说,干货为主。
  • 本文能让初学者一步解决适配问题

第一步(font-size)

  • 此步骤主要是设定font-size的大小
  • 此方案是把屏幕宽度设置为3.75rem
  • font-size根据屏幕的宽度变化而变化
(function() {
	var width = window.innerWidth / 375 * 100; //换算1rem的宽度
	document.documentElement.style.fontSize = width + "px";//fontSize的大小
})()
  • 一般UI图的宽度为375px(iphone 6的屏幕宽度)
  • 假如设计图上的宽度是200px,则你在写css就可以写为2rem

第二步(防止低版本浏览器识别不准)

  • 有些低版本浏览器(最典型的就是vivo手机,内置的浏览器内核特别低,一般不能准确识别到宽度。

html部分

<div class="wrap">
	<div class="rems"></div>
</div>

css部分

*{
    padding: 0;
    margin: 0;
}
html,body{
    width: 100%;
}
.rems{
    width: 1rem;
    height: 1px;
    z-index: -100;
}
.wrap{
    width: 100%;
				
}

 js部分

function remAgain() {
	var width = window.innerWidth / 375 * 100;
	document.documentElement.style.fontSize = width + "px";
	var rems = document.getElementsByClassName("rems")[0];
	if(rems.clientWidth != width && window.innerWidth != 0) {
	document.documentElement.style.fontSize = width / (rems.clientWidth / width) + "px";
    }
}
window.onload=function () {
	setTimeout(function () {
		remAgain();
	},0)
}

总结

  • 以上2步就可以完美解决移动端适配问题
  • 下面是完整代码
  • <!DOCTYPE html>
    <html>
    	<head>
    		<meta charset="utf-8">
    		<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    		<meta http-equiv="X-UA-Compatible" content="ie=edge">
    		<meta http-equiv="pragma" content="no-cache">
    		<meta http-equiv="Cache-Control" content="no-cache, must-revalidate">
    		<meta http-equiv="expires" content="0">
    		<script type="text/javascript">
    			(function() {
    				var width = window.innerWidth / 375 * 100;
    				document.documentElement.style.fontSize = width + "px";
    			})()
    		</script>
    		<style type="text/css">
    			*{
    				padding: 0;
    				margin: 0;
    			}
    			html,body{
    				width: 100%;
    			}
    			.rems{
    			    width: 1rem;
    			    height: 1px;
    			    z-index: -100;
    			}
    			.wrap{
    				width: 100%;
    				
    			}
    		</style>
    	</head>
    	<body>
    		<div class="wrap">
    			<div class="rems"></div>
    		</div>
    	</body>
    	<script type="text/javascript">
    		//计算rem  (兼容识别rem不准问题)
    		function remAgain() {
    			var width = window.innerWidth / 375 * 100;
    			document.documentElement.style.fontSize = width + "px";
    			var rems = document.getElementsByClassName("rems")[0];
    			if(rems.clientWidth != width && window.innerWidth != 0) {
    				document.documentElement.style.fontSize = width / (rems.clientWidth / width) + "px";
    			}
    		}
    		window.onload=function () {
    			setTimeout(function () {
    				remAgain();
    			},0)
    		}
    	</script>
    </html>
    

猜你喜欢

转载自blog.csdn.net/qq_42089654/article/details/83011274