码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-06-30 17:11:00      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:viewport   doc   导致   自适应   3.2   logs   auto   width   dev   

<!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高度自适应(可设置最大高度)

标签:viewport   doc   导致   自适应   3.2   logs   auto   width   dev   

原文地址:http://www.cnblogs.com/Gaoswatou/p/7099054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!