屏幕适配方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>大屏适配方案</title>
<style>
* {
margin: 0;
height: 0;
}
#app {
background-color: red;
/* 这里必须设置好宽高,跟设计稿保持一致 */
width: 1920px;
height: 968px;
/* 通过定位和平移, 让页面内容保持居中 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* 修改transform的参照点, 默认是中心点,如果不修改的话会相对于设计稿居中
只有通过这样让其相对于左上角操作再通过上面的方法才能保持在任何屏幕都居中显示
*/
transform-origin: left top;
}
</style>
</head>

<body>
<div id="app"></div>
<script>
// * 设计稿尺寸
let baseWidth = 1920
let baseHeight = 968 // 这是减去浏览器顶部导航栏的高度之后的结果
// let baseHeight = 1080
let timer = null // 定时器

// * 设计稿宽高比 1.77778
let baseRate = (baseWidth / baseHeight).toFixed(5)

// * 缩放比例
let scale = {
width: '1',
height: '1'
}

const resizeDraw = () => {
// 获取当前宽高
let innerWidth = window.innerWidth
let innerHeight = window.innerHeight
// 获取当前宽高比
let innerRate = parseFloat((innerWidth / innerHeight).toFixed(5))
if (innerRate > baseRate) {
// 说明屏幕更宽
let rate = (innerHeight / baseHeight).toFixed(5)
scale.width = rate
scale.height = rate
} else {
// 说明屏幕更高
let rate = (innerWidth / baseWidth).toFixed(5)
scale.width = rate
scale.height = rate
}
document.getElementById("app").style.transform = `scale(${scale.width}, ${scale.height}) translate(-50%, -50%)`
}

const resize = () => {
clearTimeout(timer)
timer = setTimeout(() => {
resizeDraw()
}, 200)
}

resizeDraw()
window.addEventListener('resize', resize)
</script>
</body>

</html>

!!! 尽量不要用vh、vw这种单位,否则 resize 后会有问题