最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to autosize contenteditable element? - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Nov 13, 2013 at 7:40 hh54188 asked Nov 13, 2013 at 7:34 hh54188hh54188 15.7k35 gold badges116 silver badges192 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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>
发布评论

评论列表(0)

  1. 暂无评论