如何改变宽度和高度的文本区域,根据其内容的大小

How to change the width and height of a textarea according to the size of its content?

本文关键字:区域 文本 改变 高度 何改变      更新时间:2023-09-26

文本区域的高度和宽度是否可以根据其内容进行更改?不需要滚动条。

HTML:

<td valign="top" width="100%">
    <textarea class="msg"> everything is good.. </textarea>
</td>
CSS:

.msg{
    padding:20px;
    color:#fff;
    font-size:18px;
    height:auto;
    line-height:30px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    white-space:normal;
    word-wrap:break-word;
    resize:none;
    overflow:hidden;
}

您可以使用scrollWidthscrollHeight来更新元素的样式,以匹配其内容的尺寸。

元素。scrollWidth read-only属性返回元素内容的宽度(以像素为单位)或元素本身的宽度,以较大者为准。如果元素的宽度大于其内容区域(例如,如果有滚动条用于滚动内容),则scrollWidth大于clientWidth。

元素。scrollHeight read-only属性用于测量元素内容的高度,包括由于溢出而无法在屏幕上显示的内容。scrollHeight值等于元素所需的最小clientHeight,以便在不使用垂直滚动条的情况下适合视点中的所有内容。它包括元素的padding,但不包括它的margin。

使用jQuery:

var msg = $('.msg');
msg.css('width',  msg[0].scrollWidth);
msg.css('height', msg[0].scrollHeight);

然而,当内容变小时,它似乎并没有收缩。

我们可以通过在检查尺寸之前强制一个更小的尺寸来缩小它,本质上是重置最小可能的尺寸。

msg.css('width',  1);
msg.css('height', 1);
msg.css('width',  msg[0].scrollWidth);
msg.css('height', msg[0].scrollHeight);