一、可直接在 菜鳥教程網站測試頁面中測試javascript
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <title>菜鳥教程(runoob.com)</title> </head> <body> <textarea style="width: 200px;padding:0px;" id="symptomTxt" oninput="autoTextAreaHeight(this)" > </textarea> </body> <script type="text/javascript"> //文本域自適應 function autoTextAreaHeight(o) { o.style.height = o.scrollTop + o.scrollHeight + "px"; } $(function () { var ele = document.getElementById("symptomTxt"); autoTextAreaHeight(ele); }) </script> </html>
二、其實這個段代碼有些小瑕疵,輸入的時候,高度自適應,可是足字刪除輸入的內容時,高度就不自適應了html
本人改進辦法,因爲時間倉促,可能不是很好,若是你有好的方式,能夠告訴我,在這裏謝謝了。java
解決:由於文本域寬度200px,測試了下,每行能輸入15個漢字,length長度爲30。因此我監聽輸入的長度,當大於30時就追加文本域高度。jquery
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <title>菜鳥教程(runoob.com)</title> </head> <body> <textarea style="width: 200px;padding:0px;" id="symptomTxt" oninput="autoTextAreaHeight(this)" > </textarea> </body> <script type="text/javascript"> //獲取文本長度,一個漢字長度爲2 var strLength = {}; strLength.GetLength = function(str) { return str.replace(/[\u0391-\uFFE5]/g,"aa").length; //先把中文替換成兩個字節的英文,在計算長度 }; //文本域自適應 function autoTextAreaHeight(o) { var element = $(o).val(); var len = strLength.GetLength(element); var rows = Math.ceil(len/30); o.style.height = o.scrollTop + 30 + (rows>0?rows-1:rows)*10 + "px"; //o.style.height = o.scrollTop + o.scrollHeight + "px"; } $(function () { var ele = document.getElementById("symptomTxt"); autoTextAreaHeight(ele); }) </script> </html>