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>

 

這方面資料不多,因此我也不是很明白是爲啥。暫且先這樣解決吧。

相關文章
相關標籤/搜索