contenteditable和user-modify实现模拟input高度自适应

文章2019-07-31147 人已阅来源:网络

contenteditable和user-modify实现模拟input高度自适应

下面是一个简单的整体优化过的示例,来看看实际效果:

运行代码
<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name=Copyright content=Tencent>
        <meta http-equiv=X-UA-Compatible content="IE=Edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>contenteditable和user-modify实现模拟input高度自适应-www.tonjay.com</title>
    </head>
    <style>
        *{  font-family: -apple-system, SF UI Text, PingFang SC, Arial, Hiragino Sans GB, Microsoft YaHei, WenQuanYi Micro Hei, sans-serif;}
        body{ background: #eee;}
        .tonjay{background: #fff; padding: 20px; width: 320px; margin: 20px auto; border:1px solid #ddd; border-radius: 3px;}
        .tonjay div+div{ margin-top: 20px;}
        .contenteditable{ background: #fafafa; padding:10px 15px; word-break: break-all;}
        .contenteditable:empty::before{content:attr(placeholder); cursor: text; color: #999;}
        .contenteditable:hover{ background: #eee;}
        .userModify{background: #fafafa; padding: 10px 15px; word-break: break-all; -webkit-user-modify:read-write-plaintext-only;}
        .userModify:empty::before{content:attr(placeholder); cursor: text; color: #999;}
        .userModify:hover{ background: #eee;}
    </style>
    <body>
        <div class="tonjay">
            <div class="contenteditable" placeholder="这是个contenteditable伪input啊,输入几个字试试" contenteditable="plaintext-only"></div>
            <div class="userModify" placeholder="这是个user-modify伪input啊,输入几个字试试"></div>
        </div>
    </body>
</html>

contenteditable

为了使元素可编辑,你所要做的就是在html标签上设置contenteditable属性,它几乎支持所有的HTML元素。

<div contenteditable="plaintext-only"></div>

先来看看它所支持的属性值吧:

contenteditable=""
contenteditable="events"
contenteditable="caret"
contenteditable="plaintext-only"
contenteditable="true"
contenteditable="false"

user-modify

大家都知道contenteditable是通过html属性来实现的,而user-modify是通过css样式来实现的。

.demo{-webkit-user-modify:read-write-plaintext-only;}

但是,此属性只支持webkit内核,firefox不支持。而且是非标准的不推荐的,此属性已被contenteditable属性取代。可以作为一个临时解决方案。

user-modify所支持的属性值:

user-modify: read-only;
user-modify: read-write;
user-modify: write-only;
user-modify: read-write-plaintext-only;