Textarea自动调整高度

时间:2016-05-12 16:28:30

标签: javascript html css

我需要自动调整文本区域的高度。默认情况下,它将是单行。在增长文本的同时,还需要增加高度。请用css向我推荐。或者用简单的jave脚本告诉我。

代码是:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<style>
textarea {
    resize: none;
    overflow: auto;
    min-height: 24px;
    max-height: 100px;
}
 #url{   word-break: break-all;
    font-family: 'Lato', sans-serif;
    cursor: text;
    resize: none;
    height: 24px;
    font-size: 14px;
    line-height: 22px;
    background-color: transparent;
    border: 0;
    margin-top: 6px;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
    text-decoration: none;
    width:500px}
</style>
<body>
<textarea readonly id="url">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</textarea>
<div>
                                                    Where does it come from?</div>
</body>

</html>

2 个答案:

答案 0 :(得分:7)

这可以使用textarea上的onkey事件轻松完成

function adjustHeight(ctrl) {
  $(ctrl).css({'height':'auto','overflow-y':'hidden'}).height(ctrl.scrollHeight);
}
$('textarea').each(function () {
  adjustHeight(this);
}).on('input', function () {
  adjustHeight(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>Your text will come here, This has a long text and it got adjusted according to the content size</textarea>

<textarea placeholder="Type, paste, cut text here..."></textarea>

答案 1 :(得分:0)

这可以&#34;伪造&#34;通过创建contenteditable容器。

fiddle

要记住的一件事是,这将不再被视为表单元素,因此需要JavaScript来提取值。