简介
最近接到需求实现类似笔记本横线的 textarea,这里简单写写实现思路。
预览

分析
- 使用
linear-gradient绘制网格线: 调整渐变色起止点,如下css可产生的效果:
background: linear-gradient(red 80%, blue 0);

调整颜色与起始点:
background: linear-gradient(transparent 95%, #424949 0);
- 设置行高与
background-size,使得背景与textarea可以进行对应:
line-height: 1.5em;
background-size: 100% 1.5em;
- 让背景跟随
textarea滚动:
background-attachment: local;
- 调整其他细节。
完整代码
index.html:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Notebook</title>
<style>
.note-book {
width: 240px;
margin: 0 auto;
background: #FEF9E7;
padding: 16px 24px;
border-radius: 4px;
box-shadow: 0 0 4px #B2BABB;
}
.note-book .cntr {
/* 实现横线效果 */
background: linear-gradient(transparent 95%, #424949 0);
line-height: 1.5em;
background-size: 100% 1.5em;
background-attachment: local; /* 这里需要根据 textarea 的内容进行滚动 */
/* textarea样式修改 */
width: 100%;
resize: none;
font-size: 0.9em;
font-family: inherit;
outline: none;
border: none;
color: #2874A6;
word-break: break-all;
overflow-x: hidden;
}
</style>
</head>
<body>
<div class="note-book">
<textarea name="note" cols="30" rows="15" class="cntr">我们遇到什么困难也不要怕,微笑着面对它!消除恐惧的最好办法就是面对恐惧!坚持,才是胜利。加油!奥利给!</textarea>
</div>
</body>
</html>