div類比textarea自適應高度,divtextarea自適應
之前在公司做項目的時候,有這麼一個需求,要我寫一個評論框,可以隨著評論的行數增加而自動擴大,最開始我想用textarea實現,但是後來嘗試後發現textarea並不適合,textarea的高度不會隨著輸入行數的增多而增大,於是我上網尋求了下協助,發現大神張鑫旭的這篇文章《div類比textarea文本域輕鬆實現高度自適應》,成功解決我的問題
代碼如下:
1 1 <!DOCTYPE html> 2 2 <html lang="en"> 3 3 <head> 4 4 <meta charset="UTF-8"> 5 5 <title>div類比textarea自適應高度le> 6 6 <style type="text/css"> 7 7 .test_box{ 8 8 width:500px; 9 9 min-height:200px;10 10 max-height:600px;11 11 _height:200px;/*相容IE6瀏覽器*/12 12 margin:0 auto;13 13 padding:3px;14 14 outline:0;15 15 border:1px solid #e4e4e4;16 16 font-size:12px;17 17 word-wrap:break-word;/*用於英文文本自動換行,所有主流瀏覽器支援*/18 18 overflow-x:hidden;19 19 overflow-y:auto;20 20 -webkit-user-modify: read-write-plaintext-only;21 21 }22 22 </style>23 23 </head>24 24 <body>25 25 <div class="test_box" contenteditable="true">我是類比textarea的div</div>26 26 <script type="text/javascript">27 27 if (typeof document.webkitHidden == "undefined") {28 28 // 非chrome瀏覽器阻止粘貼29 29 box.onpaste = function() {30 30 return false;31 31 }32 32 }33 33 </script>34 34 </body>35 35 </html>
其中有一兩個從沒見過的屬性:
- -webkit-user-modify: read-only | read-write | read-write-plaintext-only
| read-only |
內容唯讀。 |
| read-write |
內容可讀寫。 |
| read-write-plaintext-only |
內容可讀寫,但粘貼內容中的富文字格式設定(如文本的顏色、大小,圖片等)會丟失。內容類別似於以純文字顯示。 |
- contenteditable 屬性規定是否可編輯元素的內容。
| true |
規定可以編輯元素內容。 |
| false |
規定無法編輯元素內容。 |
再次感謝鑫大神(http://www.zhangxinxu.com/),分享了好多非常實用的經驗,等將來能達到他那種高度,我也想寫出好部落格分享出來造福人類,哈哈,雖然還很遙遠,繼續fighting~