首页 > 代码库 > textarea高度自适应(可设置最大高度)

textarea高度自适应(可设置最大高度)

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <meta http-equiv="X-UA-Compatible" content="ie=edge">  <title>textarea设置高度自适应且可设置最大高度</title>  <style>    textarea {      width: 100%;      height: 38px;      /*最初高度设置为38px;在输入时,会自动换行,高度自适应,直到最大高度*/    }  </style>  <script src="./jquery-3.2.1.min.js"></script></head><body>  <div style="width:300px;height:200px">    <textarea></textarea>  </div></body><script>  var setTextareaMH = function (max_height) {    $(textarea).each(function () {      this.setAttribute(style, height: + (this.scrollHeight) + px;overflow-y:hidden;);      if (max_height != 0) {        this.setAttribute(style, max-height: + max_height + px);      }    }).on(input, function () {      this.style.height = auto;      this.style.height = (this.scrollHeight) + px;    });  }  $(document).ready(function () {    // var textMaxH = ‘0‘    var textMaxH = 150 //设置最大高度为150    setTextareaMH(textMaxH) //当textMaxH设置为0时,则不对textarea设置最大高度  });</script></html>

 

PS:设置高度或者最大高度,会存在几px的误差,这是textarea的边框或啥(其实我也不知道啥。。ooo)导致的。

 

G~G~ Study。

textarea高度自适应(可设置最大高度)