纯CSS方式
使用@media标签,检测设配参数
优势:只需要CSS就能实现;
不足:只能做样式层面的改动;
// html
<div class="box"></div>
// css
.box {
width: 100px;
height: 100px;
border: 1px solid black;
background: blue;
}
@media screen and (min-width: 1980px) {
.box {
background: red;
}
}
@media screen and (max-width: 1980px) and (min-width: 720px) {
.box {
background: green;
}
}
Window.matchMedia()
原生JS解决不同媒体条件下的样式
优点:支持不同媒体条件下,不同的样式以及JS操作;
// html
<div class="box"></div>
//css
.box {
width: 100px;
height: 100px;
border: 1px solid black;
}
//js
const small = window.matchMedia('(max-width: 720px)').matches;
const big = window.matchMedia('(min-width: 1980px)').matches;
const color = small
? 'blue'
: big
? 'red'
: 'green';
document.querySelector(".box").style.background = color;
react-responsive
用法与Window.matchMedia()类似,也是传入媒体查询字符串,返回是否符合查询条件;
优点:和React结合紧密
//React
import React from 'react';
import { useMediaQuery } from 'react-responsive'
function App() {
const big = useMediaQuery({ query: '(min-device-width: 1980px)' });
const small = useMediaQuery({ query: '(max-width: 720px)'});
const color = small
? 'blue'
: big
? 'red'
: 'green';
return (
<div>
<div className="box" style={{ backgroundColor: color }} />
</div>
);
}
ReactDOM.render((
<App />
), mountNode);