Here is my contenteditable element:

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

I want it can autosize according to the user's content. I try to listen to keyup event:

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

this could work when the div grow higher, but when user delete all content, the div can't be shorter.

How can I let it be autosize?

DEMO here

有帮助吗?

解决方案

Add "display: inline-block;" to your CSS and and "min-" to width and height.

Your DIV will automatically grow the innerHTML content.

<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>

其他提示

Look at this fiddle:DEMO

This is working fine...

you just use the following HTML tag in your code

<div contenteditable="true"  style= "border: 1px solid red; min-height:30px;width:200px"></div>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top