blog-web/source/_posts/前端杂烩/响应式布局.md
2018-05-10 09:47:30 +08:00

97 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 响应式布局
date: 2018-4-6 10:55:37
tags:
- 前端
- css
categories:
- 前端杂烩
---
#### 媒体查询
媒体查询可以使用`@media`在css样式当中进行断点 , 让指定的css样式按照要求进行生效
```css
@media (max-width:768px) {
.box {
color : red;
}
}
```
上面写在媒体查询当中的css代码 , 在页面视窗宽度小于768px时生效
<!-- more -->
##### 根据媒体类型进行断点
+ all 所有设备
+ print 用于打印机和打印预览
+ screen 用于电脑屏幕 平板电脑 智能手机等
+ speech 屏幕阅读器等发声设备
##### 逻辑操作符
使用逻辑操作符可以构建复杂的媒体查询 , 有`and` , `not` , `only`
```css
@media (min-width: 700px) and (orientation: landscape) {
/* 宽度大于700并且横屏的时候应用该效果 */
.box1 { color: red; }
}
```
只用于屏幕显示( 打印输出不生效 )
```css
@media only screen and (max-width:1150px){
div{border:solid 1px;}
}
```
##### 按需加载CSS
其实与上面的媒体查询作用是一样的 , 只不过在页面引入css时添加媒体查询条件
```xml
<link type="text/css" rel="stylesheet" href="base.css" media="(max-width:500px)"/>
```
浏览器在执行渲染的时候 , 实际和媒体查询是一样的 , 相当于给整个文件当中的css包装了一层媒体查询
#### REM
这是一个应用于长度的单位 , 所有可以用长度值来声明的CSS样式 , 都可以以它当做单位 , 比如width , font-size等等
这个单位代表的是相对于`html``font-size`的值
比如
```css
html {
font-size:100px;
}
body {
/* 为了防止元素继承html的字号,干扰全局样式,所以重置为默认 */
font-size:initial;
}
.box2 {
width : 0.5rem;
}
```
那么box2的实际宽度就是 0.5 × 100px = 50px
基于这种机制 , 我们就可以编写页面`resize事件`的回调函数
在函数当中获取当前视窗的宽度与高度 , 去动态改变根元素(html节点)的font-size的值
从而让页面中的元素适应视窗大小的变化
( 假定设计稿给出的宽度是750px )
```javascript
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
```
#### 设置viewport的width
这种方案 , 就是直接指定viewport的width大小
```xml
<meta name="viewport" content="width=750" />
```
但是使用了这种方案之后
因为已经将宽度定死了 , 所以针对宽度执行的媒体查询就会失效
存在很大的弊端
而使用REM方案是可以使用媒体查询的