自适应布局
自适应布局是不同设备对应不同的html(局部自适应),通过判断设备的类型或控制局部的变化。
1、获取设备是移动端还是pc端
// 获取设备的信息
let userAgent = navigator.userAgent.toLowerCase();
// 使用正则表达式来判断类型
let device = /ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/;
if (device.test(userAgent)) {
console.log('移动端')
} else {
console.log('PC端')
}
2、flex与media结合
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.father {
width: 100%;
display: flex;
font-size: 30px;
text-align: center;
}
.father :nth-child(1) {
background-color: yellow;
flex: 0 0 80px;
}
.father :nth-child(2) {
background-color: red;
flex: 1 1 auto;
}
.father :nth-child(3) {
background-color: yellow;
flex: 0 0 80px;
}
@media screen and (min-device-width:400px) and (max-device-width:500px) {
.father :nth-child(2) {
background-color: rgb(0, 247, 255);
flex: 1 1 auto;
}
}
@media screen and (min-device-width:200px) and (max-device-width:399px) {
.father :nth-child(2) {
background-color: rgb(179, 255, 0);
flex: 1 1 auto;
}
}
</style>
</head>
<body>
<div class="father">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
</body>
</html>