移动端的适配
移动端的一些关键术语
-
物理像素:其实就是屏幕的分辨率
-
设备独立像素:就是设备的宽度
-
css像素:就是px 是相对长度 CSS 像素是 Web 编程的概念,指的是 CSS 样式代码中使用的逻辑像素
-
视网膜屏:视网膜屏幕是分辨率超过人眼识别极限的高分辨率屏幕,由苹果公司在2010年在iPhone 4发布会上首次推出
-
设备像素比dpr : dpr = 物理像素 / 设备独立像素 = 屏幕分辨率 / 设备宽度
常见的手机像素:
iphone 6 7 8 :
设备独立像素 : 667 * 375 分辨率: 1334x750 dpr: 2
iphone 5 ;
设备独立像素 : 320 * 568 分辨率: 1136*640 dpr:2
iphone 6 7 8plus:
设备独立像素 : 414 * 736 分辨率: 1920×1080 dpr: 3
安卓手机:
设备独立像素: 360 * 640 分辨率 1920×1080 dpr:3
移动端的设计稿
移动端的设计稿:
分为 640 750(通常都是750) 1124
移动端的设计稿都是参照的 phone 678 手机机型设置的: 750px
进行移动端开发: 选择的开发模型 phone 6 7 8 : 375 * 667
移动端的适配–媒体查询
适配步骤:
-
设置meta标签
-
进行移动端适配换算
移动端的开发,单位是rem
要把px单位换算成rem
进行移动端适配换算
设计稿: 750px ====> 宽度 375px
假设1rem =100px
设置 html的 fontsize = 100px
那么 750px就等于7.5rem 宽度375px = 3.75rem
移动端的屏幕适配换算
进行适配: html fontsize = (device-width * 100 / 750) px
device-width:是设备的宽度
案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<title>Document</title>
<style>
html {
font-size: 100px;
}
* {
margin: 0;
padding: 0;
}
@media(width:414px) {
html {
font-size: 55.2px;
}
}
@media(width:375px) {
html {
font-size: 50px;
}
}
@media(width:320px) {
html {
font-size: 42.67px;
}
}
@media(width:360px) {
html {
font-size: 48px;
}
}
.wrap {
width: 7.5rem;
height: 3.75rem;
background-color: red;
}
</style>
</head>
<body>
<div class="wrap"></div>
</body>
</html>
移动端的屏幕适配js实现
<!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>
* {
margin: 0;
padding: 0;
}
.box {
width: 7.5rem;
height: 1rem;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
function resizeEvent() {
// 获取根元素html
let html = document.documentElement;
// 获取宽度
let wd = html.clientWidth;
// let wd = html.getBoundingClientRect().width
// 进行判断
if (wd > 750) {
wd = 750
}
// 根据不同的屏幕,设置根元素的字体大小
// html.style.fontSize = wd * 100 / 750 + 'px';
html.style.fontSize = wd / 7.5 + 'px';
}
resizeEvent();
// 性能考虑
let time = null;
// 监听事件
window.addEventListener('resize', function () {
time && clearTimeout(time)
time = setTimeout(resizeEvent, 300)
})
// // 监听 dom 加载事件
// document.addEventListener('DOMContentLoaded', resizeEvent)
// // 移动端的横竖屏切换:
// window.addEventListener("orientationchange",resizeEvent);
// let resizeEvt = window.orientation ? 'orientationchange' : 'resize'
// window.addEventListener(resizeEvt,resizeEvent);
</script>
</body>
</html>