1 如何适配屏幕
1.1 算法
- Wp 为页面有效宽度,Hp 为页面有效高度
- 页面左右居中,上下居中,四周留白即可
- 然后在 head 里用 JS 设置 1rem = Wp / 100
// 设备宽度
const clientWidth = document.documentElement.clientWidth
// 设备高度
const clientHeight = document.documentElement.clientHeight
// 页面宽度
const.pageWidth = clientWidth / clientHeight > 16 / 9
? clientHeight * (16 / 9)
: clientWidth
// 页面高度
const pageHeight = pageWidth / (16 / 9)
// 让一个rem是有效宽度的1%
1.2 使用 rem
获取设备宽高,并得到页面宽高。
const clientWidth = document.documentElement.clientWidth // 得到设备宽度
const clientHeight = document.documentElement.clientHeight // 得到设备高度
const pageWidth = clientWidth / clientHeight > 16 / 9 ? clientHeight * (16 / 9) : clientHeight; // 定义页面宽度
const pageHeight = pageWidth / (16 / 9) // 定义页面高度
复制代码
设置 1rem = Wp / 100。
const string = `<style>html{font-size: ${pageWidth/100}px}</style>`
document.write(string)
用 rem 表达页面宽度。
假设某div在设计稿中长100px,设计稿整体宽度2420px。那么该div在页面中长为100 / 1920 * 100rem。
1.3使用 px() 函数
按照上方公式,新建一个px.ts文件,声明全局函数px()并导出。
export const px = (n) => n / 2420 * (window as any).pageWidth;
2 使用echart
2.1 引入
import * as echarts from "echarts";
2.2 写方法
举例:
useEffect(() => {
var myChart = echarts.init(divRef.current);
myChart.setOption(createEchartOptions({
color: ['#8D70F8', '#33A4FA'],
xAxis: {show: false},
yAxis: {show: false},
legend: {show: false},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['75%', '90%'],
avoidLabelOverlap: false,
label: {
show: true, position: 'inside', textStyle: {color: 'white', fontSize: px(20)},
formatter(options) {
return options.value * 100 + '%';
}
},
labelLine: {show: false},
itemStyle: {
borderColor: '#0F113A',
borderWidth: px(4)
},
data: [
{value: 0.2, name: '女'},
{value: 0.8, name: '男'},
]
}
]
}));
}, []);
3 使用 grid 布局
Grid 布局即网格布局,是一种新的 CSS 布局模型,比较擅长将一个页面划分为几个主要区域,以及定义这些区域的大小、位置、层次等关系。
通过上面的例子Grid 布局相关的属性以及值众多,需要记忆的不少,建议可以跟 demo 一起结合起来,边敲代码边理解,再利用一些空闲时间记忆一下。
使用grid布局将页面分成几块。
<main>
<section className="section1"></section>
<section className="section2"></section>
<section className="section3"></section>
<section className="section4"></section>
<section className="section5"></section>
</main>
>main {
display: grid;
grid-template:
"box1 box2 box4 box5" 755fr
"box3 box3 box4 box5" 363fr / 366fr 361fr 811fr 747fr;
grid-column-gap: px(28);//行空隙
grid-row-gap: px(28);//列空隙
>.section1 {
grid-area: box1;
background: pink;
}
>.section2 {
grid-area: box2;
background: lightgrey;
}
>.section3 {
grid-area: box3;
background: lightblue;
}
>.section4 {
grid-area: box4;
background: lightcyan;
}
>.section5 {
grid-area: box5;
background: lightyellow;
}
}