为什么文本的高度不能改变

Why the height can not change of textrea

本文关键字:不能 能改变 高度 文本 为什么      更新时间:2023-09-26

有人知道为什么会这样吗?当我注释

//  $(this).css("height",height1);

thehighight1显示正确的高度文本区域当我删除或添加行,但当我取消注释这一行,警告是不正确的,即使我删除一行,高度只会越来越大。

谢谢!

我想在添加或删除行时改变textarea的高度

<textarea style="width:380px;height:auto" name="MeStatusDes" id="MeStatusDes" ></textarea>
<script>
    $("#MeStatusDes").keyup(function(e){
        height1 = this.scrollHeight +  "px";
        alert(height1);
        $(this).css("height",height1); // when I uncomment this, all alert is correct
    });
</script>

你的代码不起作用,因为当你设置新的高度时,你也增加了scrollHeight。但是,当您删除一行时,它不会这样工作,因为浏览器首先解析该函数,然后调整textarea的大小。

我只是放了一些控制台日志以便更好地解释。我所做的就是按回车键然后按退格键。

$("#MeStatusDes").keyup(function(e){
    height1 = this.scrollHeight +  "px";
    console.log('scrollHeight: ' + height1);
    console.log('current height: '+ $(this).css("height"));
    $(this).css("height",height1);
    console.log('new height: '+ $(this).css("height"));
});

按回车键时的控制台输出

scrollHeight: 36px
current height: 32px
new height: 36px

按退格键时的控制台输出

scrollHeight: 40px
current height: 36px
new height: 40px 

下面是你可能需要的:https://stackoverflow.com/a/17772322/3413052

最后我发现了这个,它可以工作,即使我不知道这个的细节。

var minRows = 5;
var maxRows = 26;
function ResizeTextarea(id) {
    var t = document.getElementById(id);
    if (t.scrollTop == 0)   t.scrollTop=1;
    while (t.scrollTop == 0) {
        if (t.rows > minRows)
                t.rows--; else
            break;
        t.scrollTop = 1;
        if (t.rows < maxRows)
                t.style.overflowY = "hidden";
        if (t.scrollTop > 0) {
            t.rows++;
            break;
        }
    }
    while(t.scrollTop > 0) {
        if (t.rows < maxRows) {
            t.rows++;
            if (t.scrollTop == 0) t.scrollTop=1;
        } else {
            t.style.overflowY = "auto";
            break;
        }
    }
}
var minRows = 5;
var maxRows = 26;
 function ResizeTextarea(id){
  var t = document.getElementById(id);
  if (t.scrollTop == 0)   t.scrollTop=1;
  while (t.scrollTop == 0){
   if (t.rows > minRows)
    t.rows--;
   else
    break;
   t.scrollTop = 1;
   if (t.rows < maxRows)
    t.style.overflowY = "hidden";
   if (t.scrollTop > 0){
    t.rows++;
    break;
   }
  }

  while(t.scrollTop > 0){

   if (t.rows < maxRows){
    t.rows++;
     if (t.scrollTop == 0) t.scrollTop=1;
   }
   else{
    t.style.overflowY = "auto";
    break;
   }
  }
 }