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

标签 javascript html contenteditable autosize

这是我的 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 不能变短。

如何让它自动调整大小?

演示 here

最佳答案

添加“显示:内联 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>

关于javascript - 如何自动调整 contenteditable 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19947955/

相关文章:

php - 如何使用 PHP 和 MySQL 读取 Base64 格式的 blob?

java - AlertDialog 内的超链接

php - 如何使用 php 在 td 中发送 contenteditable 值

javascript - 在 contenteditable div 插入 html

javascript - d3 世界城市 map 中的城市点出现在世界地图后面

javascript - 替换变换 : translate()

javascript - 使用 contains 的 jquery 搜索无法正常工作

javascript - Spring-boot删除javascript确认消息

javascript - CSS3定位及误区使用

JavaScript document.execCommand 删除 formatBlock 格式?