初始准备(可忽略)
把file协议变成http协议:
npm i -g http-server /安装
http-server -c-1 /使用
使用
@media
媒体是什么?
电脑是个媒体,纸张是个媒体,是我们传播知识的媒体/媒介。
媒体查询就是对你的媒体进行某些条件的查询。
@media (max-width: 800px){
body{
background: red;
}
}
/如果某个媒体满足宽度是0~800之间,里面的css就生效(body就变红)
设备
设备宽度
Mobile S
320px
Mobile M
375px
Mobile L
425px
Tablet
768px
Laptop
1024px
Laptop L
1440px
/写法一:要注意优先顺序
@media (max-width: 768px){ /*0~768*/
body{
background: blue;
}
}
@media (max-width: 425px){ /*0~425*/
body{
background: green;
}
}
@media (max-width: 375px){ /*0~375*/
body{
background: orange;
}
}
@media (max-width: 320px){ /*0~320*/
body{
background: red;
}
}
@media (min-width: 769px){ /*769~*/
body{
background: purple;
}
}
/写法二: 让他们没有交集
@media (max-width: 320px){ /*0~320*/
body{
background: red;
}
}
@media (min-width: 321px) and (max-width: 375px){ /*321~375*/
body{
background: orange;
}
}
@media (min-width: 376px) and (max-width: 425px){ /*376~425*/
body{
background: green;
}
}
@media (min-width:426px) and (max-width: 768px){ /*426~768*/
body{
background: blue;
}
}
@media (min-width: 769px){ /*769~*/
body{
background: purple;
}
}
/css 外部引用文件的媒体查询
/ 只有在0~320px,css才会生效
实例
先做哪版都可以。
Mobile first: 先做手机版
desktop first 先做pc版
有人推荐使用Mobile first,理由:用户50%以上都是用手机看页面,用户优先使用手机,所以有理由优先做手机版。
代码
移动页面demo*{margin: 0; padding: 0;}
a{color: inherit; text-decoration: none;}
ul,ol{list-style: none;}
.logo{
width: 60px;
height: 60px;
background: grey;
border-radius: 30px;
}
.clearfix::after{
content: "";
display: block;
clear: both;
}
header{
padding: 10px;
position: relative;
}
.nav{
display: none;
background: gray;
margin-top: 10px;
}
.nav.active{
display: flex;
justify-content: space-between;
}
header > button{
position: absolute;
right: 20px;
top: 26px;
}
.nav{
display: none;
}
@media (max-width: 450px){ /*像素大于451的,不是手机*/
header > button{
display: none;
}
.nav, .nav.active{
display: none;
}
.nav2{display: block;}
header{
display: flex;
align-items: center;
}
header .nav2{
display: flex;
margin-left: 20px;
}
header .nav2>li{
margin: 0 10px;
}
}
菜单
menuBtn.onclick = function(){
menu.classList.toggle('active')
}
// menuBtn.onclick = function(){
// if(menu.style.display === 'block'){
// menu.style.display = 'none';
// }else{
// menu.style.display = 'block';
// }
// }
touch插件
移动端JS有touch事件,在手机屏幕摸来摸去的时候,不会触发click事件,用户希望触发滑动事件,js不支持滑动事件,但是可以通过用户摸得位置
例:第一次动的时候记下第一点位置,第二次动的时候记下第二点位置,如果第二点是在第一点的左边,说明用户在左滑;