div contenteditable placeholder

contenteditable型的编辑框,实现placeholder的方式有两种html

 

第一种,Css的实现方式:jquery

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.content{
width:380px;
height:50px;
border:1px solid #e1e1e1;
-webkit-user-modify:read-write-plaintext-only;
}
.text:empty:before{content: attr(placeholder);color:#bbb;}
.text:focus{content:none;}

</style>
</head>
<body>
<div class="content text" contenteditable="true" placeholder="你想说什么"></div>
</body>
</html>


可是,这种方式存在一个漏洞或问题:若是在编辑框里直接回车,而后再删除,就不会再出现placeholder里的提示内容了、通过分析,发现回车的时候会在web

<div class="content text" contenteditable="true" placeholder="你想说什么"></div>添加内容。this

若是加了 -webkit-user-modify:read-write-plaintext-only;则增长两个<br/>标签spa

不然加了两个<div><br/></div>标签。code

当增长的是两个<br/>标签,删除只能删除一个标签,余下一个标签,致使empty判断为false。htm

当增长的是两个<div><br/></div>标签,多按一次删除仍是能够出现提示文字,可是用户体验就不佳了。blog

 

这里确实很疑惑。毕竟我只敲了一次回车键,为啥会出现两个标签。只有第一次回车键才会出现该状况。日后就正常了、ip

因此,最终采用了第二种方式。去判断了多余的未删掉的一个标签。rem

第二种,Js的实现方式:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.content{
width:380px;
height:50px;
border:1px solid #e1e1e1;
-webkit-user-modify:read-write-plaintext-only;
}
.text::after  {
    content: attr(placeholder);
    position: absolute;
    top: 10px;
    color: #a9a9a9;
}
</style>
</head>
<body>
<div class="content text" contenteditable="true" placeholder="你想说什么"></div>
<script src="js/jquery-2.1.4.min.js"></script>
<script>

 $('.placeholder').on('input', function(){
          
     var htm = this.innerHTML;
     if (htm.length!= 0 && htm!='<br>') {
        $(this).removeClass('text');
     } else {
        $(this).addClass('text');
    }
}); 

</script>

</body>
</html>

 

这方面资料不多,因此我也不是很明白是为啥。暂且先这样解决吧。

相关文章
相关标签/搜索