div模擬textarea自適應高度

  以前在公司作項目的時候,有這麼一個需求,要我寫一個評論框,能夠隨着評論的行數增長而自動擴大,最開始我想用textarea實現,可是後來嘗試後發現textarea並不適合,textarea的高度不會隨着輸入行數的增多而增大,因而我上網尋求了下幫助,發現大神張鑫旭的這篇文章《div模擬textarea文本域輕鬆實現高度自適應》,成功解決個人問題javascript

代碼以下:css

 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>

其中有一兩個從沒見過的屬性: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~java

相關文章
相關標籤/搜索