简体   繁体   中英

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

Is there any way for the height and width of a textarea to change according to its content? The scrollbar is no needed.

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;
}

You can use scrollWidth and scrollHeight to update the style of your element to match its content's dimensions.

The Element.scrollWidth read–only property returns either the width in pixels of the content of an element or the width of the element itself, whichever is greater. If the element is wider than its content area (for example, if there are scroll bars for scrolling through the content), the scrollWidth is larger than the clientWidth.

The Element.scrollHeight read-only attribute is a measurement of the height of an element's content, including content not visible on the screen due to overflow. The scrollHeight value is equal to the minimum clientHeight the element would require in order to fit all the content in the viewpoint without using a vertical scrollbar. It includes the element padding but not its margin.

Using jQuery:

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

However, it doesn't seem to shrink back when the content becomes smaller.

We can make it shrink by forcing a smaller size before checking the dimensions, essentially resetting the minimum possible size.

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

Demo in this JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM