一.介绍
在前端项目页面开发中,尤其是H5页面开发,我们常常要适配各种分辨率的屏幕,才能让用户获得最好的体验效果.pc也是如此,很多页面是一屏,也是要适配各种尺寸的分辨率.这时候我们就需要对各种分辨率的手机电脑进行适配.那么用什么适配方案比较好呢?下面给大家介绍一种我觉得比较好的适配方案.
二、分辨率
常用的分辨率可以大致分为这些,手机:320-750(320-768)
ipad:750-1080(768-1080) pc:1080-1440 1440-1920 1920-2560 2560-3440
3440-5120
。适配的基础通常还是要根据设计稿来决定,比如pc的设计稿宽度是1920,那么你的适配方案只能是1080-1920之间去适配,不能适配大于1920的。那么大于1920的适配,我们就通常采取水平居中,空白地方采用背景平铺或者使用主题色平铺.
三、适配脚本代码
1 (function() {
2 window.onload = window.onresize = () => {
3 let clientWidth = document.body.clientWidth;
4 // console.log(clientWidth,'clientWidth');
5 if (clientWidth >= 750) {
6 /* 适配pc页面 最小适配分辨率 12/(20/1920) = 1152 */
7 var size = 20 * clientWidth / 1920 + 'px';
8 document.documentElement.style.fontSize = size;
9 } else {
10 /* 淘宝移动端适配解决方案 */
11 (function flexible(window, document) {
12 var docEl = document.documentElement;
13 var dpr = window.devicePixelRatio || 1;
14 function setBodyFontSize() {
15 if (document.body) {
16 document.body.style.fontSize = (12 * dpr) + 'px';
17 } else {
18 document.addEventListener('DOMContentLoaded', setBodyFontSize);
19 }
20 }
21 setBodyFontSize();
22 function setRemUnit() {
23 var rem = docEl.clientWidth / 10;
24 docEl.style.fontSize = rem + 'px';
25 }
26 setRemUnit();
27 window.addEventListener('resize', setRemUnit);
28 window.addEventListener('pageshow', function(e) {
29 if (e.persisted) {
30 setRemUnit();
31 }
32 });
33 if (dpr >= 2) {
34 var fakeBody = document.createElement('body');
35 var testElement = document.createElement('div');
36 testElement.style.border = '.5px solid transparent';
37 fakeBody.appendChild(testElement);
38 docEl.appendChild(fakeBody);
39 if (testElement.offsetHeight === 1) {
40 docEl.classList.add('hairlines');
41 }
42 docEl.removeChild(fakeBody);
43 }
44 }(window, document));
45 }
46 };
47 })();
四、写法
H5:设计稿750*H(H依据设计稿实现长度) 字体:18px;
@lg: 75rem;
.al_wrap{
width: 750/@lg;
height: 200/@lg;
overflow: hidden;
margin: 0 auto;
font-size: 18/@lg
}
pc:设计稿1920*H(H依据设计稿实现长度)字体:20px;距离上20px;
@lg: 20rem;
.al_wrap{
width: 1920/@lg;
height: 100/@lg;
overflow: hidden;
margin: 0 auto;
margin-top: 20/@lg;
font-size: 20/@lg
}
web前端其实很简单!
如何学习呢?看下下面
领取方法:
![](https://img.haomeiwen.com/i16256753/14eb17d0c3db8aed.png)
网友评论