编程语言
首页 > 编程语言> > javascript – 如何自动调整contenteditable元素?

javascript – 如何自动调整contenteditable元素?

作者:互联网

这是我满意的要素:

    #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不能更短.

我怎么能让它自动调整?

DEMO here

解决方法:

添加“display:inline-block;”到你的CSS和“min-”到宽度和高度.

您的DIV将自动增加innerHTML内容.

<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,autosize,javascript,contenteditable
来源: https://codeday.me/bug/20190831/1775014.html