HTML contenteditable属性
文章目录
前言
之前一直没有留意到有contenteditable这个属性,今天突然看到特意记录一下它的 用法 和 实际用途 ;
用法
为了某个使元素可编辑,你所要做的就是在html标签上设置"contenteditable"属性,它几乎支持所有的HTML元素。
contenteditable有以下几种属性:
-
"true"表明该元素可编辑 -
"false"表明该元素不可编辑 -
"inherit"(默认)表明该元素继承了其父元素的可编辑状态
<div contenteditable="true">
This text can be edited by the user.
</div>
通过一下代码,可以观察到如果子元素没有设置contenteditable属性,其默认值继承自父元素(既默认为"inherit"属性)
<div contenteditable="true">
<p>Edit this content to add your own quote</p>
<p>Edit this content to add your own quote - 2</p>
</div>
可以使用css中caret-color属性设置文本插入光标的颜色。
实际用途
1.div模拟textarea文本域轻松实现高度自适应
2.避免处理input、textarea的内含样式
CSS user-modify
使用css中的user-modify属性,也可以让普通元素可以读写。
/* Keyword values */
user-modify: read-only; (默认值)
user-modify: read-write;
user-modify: write-only;
user-modify: read-write-plaintext-only; (只允许输入纯文本,但兼容性很差)
/* Global values */
user-modify: inherit;
user-modify: initial;
user-modify: unset;
举个例子:
<div class="readwrite">The user is able to change this text.</div>
.readwrite {
-moz-user-modify: read-write;
-webkit-user-modify: read-write;
}
相对于contenteditable而言,user-modify的兼容性就没那么理想了。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论