textarea高度自适应增高;chrome下clientHeight,offsetHeight和scrollHeight

以下是相关代码

<!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-2.1.4.min.js"></script>
</head>

<body>
  <!-- 配置textarea高度自适应增长 到最大高度后 出现滑动条-->
  <div style="width:300px;height:200px">
    <textarea></textarea>
  </div>

  <!-- 验证chrome下clientHeight,offsetHeight, -->
  <div id="test" style="height:40px;width:200px;border:2px solid #ddd;
  margin:5px;padding:5px;overflow:auto;">
  kkkkkkkkk
  </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 = '350'; //设置最大高度为150
    setTextareaMH(textMaxH) //当textMaxH设置为0时,则不对textarea设置最大高度
  });



  var obj = document.getElementById("test");
  //内容超过容器时 chrome
  alert("obj clientHeight: " + obj.clientHeight);//33 clientHeight = padding + height - scrollbar.width(17)
  alert("obj offsetHeight: " + obj.offsetHeight);//chrome 54 offsetHeight = padding + border + height
  alert("obj scrollHeight: " + obj.scrollHeight);//72 当内容未撑开容器时高度为盒子高度,当内容撑开出现滚动条时是元素内容实际高度

  //内容未超过容器时三个高度为: 50 54 50

</script>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值