1. It can be tested directly in the test page of rookie tutorial website
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <title>Rookie tutorial(runoob.com)</title> </head> <body> <textarea style="width: 200px;padding:0px;" id="symptomTxt" oninput="autoTextAreaHeight(this)" > </textarea> </body> <script type="text/javascript"> //Text field adaption function autoTextAreaHeight(o) { o.style.height = o.scrollTop + o.scrollHeight + "px"; } $(function () { var ele = document.getElementById("symptomTxt"); autoTextAreaHeight(ele); }) </script> </html>
2. In fact, there are some small flaws in this code. When inputting, it is highly adaptive, but when deleting the input content, it is not
My improvement method may not be very good due to the short time. If you have a good way, please let me know. Thank you here.
Solution: because the width of the text field is 200px, under the test, each line can input 15 Chinese characters, and the length is 30. So I listen for the length of the input, and when it is greater than 30, I add the height of the text field.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <title>Rookie tutorial(runoob.com)</title> </head> <body> <textarea style="width: 200px;padding:0px;" id="symptomTxt" oninput="autoTextAreaHeight(this)" > </textarea> </body> <script type="text/javascript"> //Get the text length. The length of a Chinese character is 2 var strLength = {}; strLength.GetLength = function(str) { return str.replace(/[\u0391-\uFFE5]/g,"aa").length; //First, replace Chinese with two bytes of English, and then calculate the length }; //Text field adaption 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>