看到标题很多人想用只能用js来实现吧!今天介绍一个标签属性可以让一个block块元素实现可编辑,且高度随内容自适应。
contenteditable ="true/false"
定义:
顾名思义,允许用户编辑元素内容,包含任意文本,且包含子元素。
使用:
给一个普通的block元素,加上contenteditable="true" 即可:
<div style="width: 150px;" contenteditable="true">我是一个div</div>
效果:
更恐怖的是:
可以使用js获取到编辑之后的内容:
用div实现textarea效果:
最小高度为200px,最大高度为400px,y轴超出出现滚动条,x轴超出隐藏,
word-wrap: break-word 允许单词内部进行断句, 就是说 会尝试一整行显示,如果显示不下会在单词内部断开,进入下一行。
<style>
.box{
width: 200px;
padding: 10px;
outline: 0;
min-height: 200px;
max-height: 200px;
overflow-y: auto;
overflow-x: hidden;
word-wrap: break-word;
border: 1px solid #b1cc99;
}
</style>
<div class="box" contenteditable="true">我是一个div</div>
效果:
注意:
1、textarea不能随内容增加能自适应,contenteditable可以。
2、与textarea一样支持focus、blur事件,也支持focus伪类。
3、该属性还有别的属性值:
contenteditable:plaintext-only; 只能编辑纯文本内容。
contenteditable:events; 未知!!!
contenteditable:caret;未知!!!
4、其中属性值 true
和 false
是所有浏览器都支持的,而 plaintext-only
等属性值IE浏览器并不支持。
补充:
focus伪类常用于做聚焦时 输入框的样式:
*** 获取聚焦时,输入框外发光
<style>
input:focus{
background-color: #eeeeee;
border: 1px solid #cc7356;
outline: none;
box-shadow: 1px 1px 3px #cc7356;
}
</style>
<input type="text" placeholder="请输入内容···">