【问题标题】:Is it possible to make HTML textarea auto-width too? Basically both auto-width and auto-height?是否也可以使 HTML textarea 自动宽度?基本上都是自动宽度和自动高度?
【发布时间】:2021-02-17 10:53:07
【问题描述】:

有很多 StackOverflow 的自动高度文本区域示例。一个例子是这样的:

https://stackoverflow.com/a/24676492/1634905

<textarea oninput="auto_grow(this)"></textarea>

textarea {
    resize: none;
    overflow: hidden;
    min-height: 50px;
    max-height: 100px;
}

function auto_grow(element) {
    element.style.height = "auto";
    element.style.height = (element.scrollHeight)+"px";
}

是否有类似的解决方案也包含自动宽度?基本上都是自动宽度和自动高度?

当我尝试以类似方式检索element.scrollWidth 时,它继续为我提供文本区域的原始宽度。

https://jsfiddle.net/on7zasd3/


编辑:

我想我明白了。 (Ps,我不知道为什么在 StackOverflow 上之后代码格式被破坏了?)

  1. 我必须在文本区域指定cols="1"

  2. 我还必须执行 element.style.width = "auto"; 并将纹理的宽度设置为在执行高度 auto 之前。

  3. Textarea 还需要white-space: nowrap; CSS:

    函数自动增长(元素){ element.style.width = "自动"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.width = (element.scrollWidth)+"px";

     element.style.height = "auto";
     console.log(element.scrollHeight+", "+element.scrollWidth)
     element.style.height = (element.scrollHeight)+"px";
    

    }

    文本区域 { 调整大小:无; 溢出:隐藏; 最小高度:30px; 最小宽度:30px; 空白:nowrap; }

【问题讨论】:

    标签: javascript html css textarea


    【解决方案1】:

    我想我明白了。

    1. 我必须在文本区域指定cols="1"

    2. 我还必须执行element.style.width = "auto"; 并将纹理的宽度设置为在执行高度auto 之前。

    3. Textarea 还需要white-space: nowrap; CSS

      函数自动增长(元素){ element.style.width = "自动"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.width = (element.scrollWidth)+"px";

       element.style.height = "auto";
       console.log(element.scrollHeight+", "+element.scrollWidth)
       element.style.height = (element.scrollHeight)+"px";
      

      }

      文本区域 { 调整大小:无; 溢出:隐藏; 最小高度:30px; 最小宽度:30px; 空白:nowrap; }

    https://jsfiddle.net/on7zasd3/3/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 2013-09-05
      • 2013-04-06
      • 1970-01-01
      相关资源
      最近更新 更多