设置自动高度,取决于文本区域中有多少列,但显然它增加了空白空间



下面是一个jsfiddle的例子。

代码

$(document).ready(function () {
var open = false;
var openSidebar = function () {
    $('.status-text').addClass('box-height');
    open = true;
}
var closeSidebar = function () {
    $('.status-text').height($("textarea")[0].scrollHeight).removeClass('box-height');
    open = false;
}
$('.status-text').click(function (event) {
    event.stopPropagation();
    openSidebar();
});
$(document).click(function (event) {
        closeSidebar();   
});
});
html

<textarea class="status-text" placeholder="test" style="width: 100%; ">
</textarea>
css

.box-height {
height:auto;
}

这是可行的。它会根据文本的大小来增加高度,但如果我点击$(document),它会一直增加高度到textarea,你无法删除它

代替document click,为什么不在文本区域的focusout上调用它呢?

$('.status-text').focusout(function() { 
   // may be user an ID for the text area
   closeSidebar();
});

或者尝试如下:

JS

function auto_grow(element) {
    element.style.height = "5px";
    element.style.height = (element.scrollHeight)+"px";
}
CSS

.status-text {
    resize: none;
    overflow: hidden;
    min-height: 50px;
    max-height: 100px;
}
HTML

<textarea class="status-text" onkeyup="auto_grow(this)"></textarea>

要使收缩生效,在计算高度之前将textarea设置为1。总是增加高度的行为是由边距/填充引起的。如此:

var closeSidebar = function () {
    $('.status-text').height(1);
    $('.status-text').height($("textarea")[0].scrollHeight - $('.status-text').outerHeight() + $('.status-text').height()).removeClass('box-height');
    open = false;
}

最新更新