如何自动调整内容可编辑元素的大小

How to autosize contenteditable element?

本文关键字:元素 编辑 何自动 调整      更新时间:2023-09-26

这是我的内容可编辑元素:

    #editor {
        width: 200px;
        height: 30px;
        border: 1px solid red;
        overflow: hidden;
    }
    <div id="editor" contenteditable="true"></div>

我希望它可以根据用户的内容自动调整大小。我试着听keyup事件:

    editor.addEventListener("keyup", function (){
        newheight = editor.scrollHeight;
        editor.style.height = newheight + "px";
    })   

当div 变高时,这可能有效,但当用户删除所有内容时,div 不能更短。

如何让它自动调整大小?

在这里演示

将"display: inline-block;"添加到CSS中,并在宽度和高度中添加"min-"。

您的 DIV 将自动增加内部 HTML 内容。

<html>
  <style type="text/css">
    #Test
    {
      display: inline-block;
      min-width: 30px;
      min-height: 30px;
      border: 1px solid red;
      overflow: hidden;
    }
  </style>
  <div id="Test" >
    Nothing But Bigger
    And <br />
    Taller
  </div>
</html>

看看这个小提琴:演示

这工作正常...

您只需在代码中使用以下 HTML 标记

<div contenteditable="true"  style= "border: 1px solid red; min-height:30px;width:200px"></div>