用textarea自动扩展背景高度

时间:2014-11-15 00:49:55

标签: javascript jquery html css

当输入的文本调整textarea的大小时,我需要自动展开背景。我对textarea的位置有问题所以我必须使用position:absolute来正确放置它。

html:

<ul id="UL">
    <li class="newComment_row">
        <div class="userComments_photo">
            <img class="photo" src="' . $userComment_img . '" alt="" />
        </div>
        <textarea id="" class="textarea" rows="1" placeholder="Escribe un comentario..." title="Escribe un comentario..."></textarea>
    </li>
</ul>

css:

#UL {
    width: 494px;
    list-style: none outside none;
    margin: 0px;
    padding: 0px;
    border-top: 1px solid rgb(225, 226, 227);
}
.newComment_row {
    height: 32px;
    position: relative;
    width: 470px;
    background: rgb(246, 247, 248) none repeat scroll 0% 0% / auto padding-box border-box;
    border-radius: 0 0 2px 2px;
    list-style: none outside none;
    margin: 0px 12px;
    padding: 4px 0px 8px;
    rows: 1px;
}
.textarea {
    resize: none;
    width: 420px;
    font: normal normal normal 12px/15.3599996566772px Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
    position: absolute;
    padding: 8px 3px 0 3px;
    margin: 0 7px;
    overflow: hidden;
}

和自动调整textarea的jquery:

function h(e) {
    $(e).css({
        'height': 'auto',
            'overflow-y': 'hidden'
    }).height(e.scrollHeight);
}
$('textarea').each(function () {
    h(this);
}).on('input', function () {
    h(this);
});

我在这里测试http://jsfiddle.net/ttwbxwon/28/

2 个答案:

答案 0 :(得分:2)

只需将此行添加到函数h

即可

$(e).parent().height($(e).height());

你可以在这里看到它 http://jsfiddle.net/ttwbxwon/29/

答案 1 :(得分:1)

稍微优化一下CSS ......

textarea不必设置为position: absolute,而只是稍微减小宽度。而不是定义.newComment_row的高度,只需调整底部填充,使其“自然”高到你想要的高度。这是我要补充的内容:

.textarea {
    width: 416px;
    position: initial;
}
.newComment_row {
    height: auto;
    padding-bottom: 3px;
}

这是一个小提琴:http://jsfiddle.net/Niffler/une6ya96/

相关问题