div contenteditable placeholder


contenteditable型的編輯框,實現placeholder的方式有兩種

 

第一種,Css的實現方式:

<!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里的提示內容了、經過分析,發現回車的時候會在

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

如果加了 -webkit-user-modify:read-write-plaintext-only;則增加兩個<br/>標簽

否則加了兩個<div><br/></div>標簽。

當增加的是兩個<br/>標簽,刪除只能刪除一個標簽,余下一個標簽,導致empty判斷為false。

當增加的是兩個<div><br/></div>標簽,多按一次刪除還是可以出現提示文字,但是用戶體驗就不佳了。

 

這里確實很疑惑。畢竟我只敲了一次回車鍵,為啥會出現兩個標簽。只有第一次回車鍵才會出現該情況。往后就正常了、

所以,最終采用了第二種方式。去判斷了多余的未刪掉的一個標簽。

第二種,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>

 

這方面資料很少,所以我也不是很明白是為啥。暫且先這樣解決吧。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM