从简书编辑器学布局

最近在做一个富文本的模块。结合知乎和简书,最终选择了简书作为模板,在布局的时候,学到了很多东西。以前做项目的时候,我主要都是负责小模块的开发,整体布局一般是第三方UI包给出,或者组内其他人写,所以自己实践比较少。

先看下整体布局

image.png

toolbar

经过观察发现,toolbar是fixed布局,会随着整个视图的滚动而滚动。

1
2
3
4
5
6
7
8
9
10
11
<style>
#toolbar{
height: 50px;
width:100%;
background-color: #00F7DE;
position: fixed; /*主要是这个*/
margin: 0;
top:0;
}
</style>
<div id="toolbar"> 工具栏</div>

Title

简书的标题字体为30px,用的是<input>标签。

我默认用H1吧,H1大小为2em,不使用<input>标签,而使用contenteditable="true"将div设置为可编辑

1
2
3
4
5
6
7
8
9
10
<style>
#title{
height: 50px;
width: 60vw;
background-color: #9933ff;
font-size: 2em; /*H1大小为2em*/
line-height: 50px; /*字体垂直居中*/
}
</style>
<div id="title" contenteditable="true"></div>

用户输入区域

这块比较有趣,赤裸裸的欺骗大法。。。果然是各种曲线救国。。看下图:

image.png

欺骗人的感情,其实真正可编辑的区域就这么点地方,点其他地方会失去焦点。

这里也一样,将<div>标签设置为可编辑状态。

1
2
3
4
5
6
7
8
<style>
#editor{
outline: 0; /*去除边框*/
margin: 30px;
background-color: orange;
}
</style>
<div id="title" contenteditable="true"></div>

效果如下

image.png

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#toolbar{height: 50px;width:100%;background-color: #00F7DE;position: fixed;margin: 0;top:0;}
#continer{margin-top: 10vh;display: flex;justify-content:center;}
#title{height: 50px;width: 60vw;background-color: #9933ff;font-size: 2em;line-height: 50px;}
#editor{outline: 0;margin: 30px;background-color: orange;}
</style>
</head>
<body>
<div id="root">
<div id="toolbar">
工具栏
</div>
<div id="continer">
<div>
<div id="title" contenteditable="true">
</div>
<div id="editor" contenteditable="true">
</div>
</div>
</div>
</div>
</body>
</html>

增加需求

需要在编辑区右侧增加几个给用户操作的按钮。上面的continer右侧增加几个用户操作按钮,可以随页面滚动,但是fixed会跟continer的flex布局冲突,目前没有更好的想法,只能暂时使用margin-left来处理。

最后效果如下:

image.png

所有代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#toolbar{height: 50px; width:100%;background-color: #00F7DE;position: fixed;margin: 0;top:0;}
#continer{margin-top: 10vh;display: flex;justify-content:center;}
#title{height: 50px;width: 60vw;background-color: #9933ff;font-size: 2em;line-height: 50px;}
#editor{outline: 0;margin: 30px;background-color: orange;}
#operation{position: fixed;z-index: -1;/*防止遮挡title输入*/}
#operation button{display: block;margin-left: 68vw;}
</style>
</head>
<body>
<div id="root">
<div id="toolbar">工具栏</div>
<div id="continer">
<div>
<div id="title" contenteditable="true">
</div>
<div id="editor" contenteditable="true">
</div>
</div>
<div id="operation">
<button>保存</button>
<button>发布</button>
<button>详细信息</button>
</div>
</div>
</div>
</body>
</html>