只有用CSS才能扩展一个textarea?

我有一个高度为200px的textarea,但是当我用文本传递200px时,我希望扩展textarea而不是用滚动条保持200px的高度。

只有用CSS才能做到这一点?

可以使用div和contentEditable属性来代替textarea

标记:

 <div contentEditable="true"></div> 

CSS:

 div { display:inline-block; border: solid 1px #000; min-height: 200px; width: 300px; } 

DEMO

用户可以使用CSS扩展textarea。 事实上,在一些现代浏览器中,这种可扩展性甚至是浏览器的默认设置。 你可以明确地要求:

 textarea { resize: both; } 

浏览器支持正在增长,但仍然有限。

关于可调整性通常只是一个小小的提示:右上angular的resize手柄。 而且恐怕大部分用户都不会理解这个提示。

你不能让textarea只使用CSS 自动扩展内容。

不,这是不可能的,只能用CSS,但你可以使用jQuery:

 $('#your_textarea').on('keydown', function(e){ var that = $(this); if (that.scrollTop()) { $(this).width(function(i,h){ return h + 20; }); } }); 

下面是一个简单的,纯粹的PHP和HTML解决scheme,不需要JS,使textarea适合大小。 HTML: <textarea rows="<?php echo linecount($sometext, 100, 3);?>" cols="100" name="sometext"><?php echo $sometext;?></textarea>

  <?php /* (c)MyWeb.cool, 2014 * ------------------------------------------------------------------------- *Calculate number of rows in a textarea. * Parms : $text: The contents of a textarea, * $cols: Number of columns in the textarea, * $minrows: Minimum number of rows in the textarea, * Return: $row: The number of in textarea. * ---------------------------------------------------------------------- */ function linecount($text, $cols, $minrows=1) { // Return minimum, if empty` if ($text <= '') { return $minrows; } // Calculate the amount of characters $rows = floor(strlen($text) / $cols)+1; // Calculate the number of line-breaks $breaks = substr_count( $text, PHP_EOL ); $rows = $rows + $breaks; if ($minrows >= $rows) { $rows = $minrows; } // Return the number of rows return $rows; } ?> 

“而这个更短,更好:

 function linecount($text, $cols, $minrows=1) { if ($text <= '') {return $minrows;} $text = wordwrap($text, $cols, PHP_EOL); $rows = substr_count( $text, PHP_EOL )+1; if ($minrows >= $rows) {$rows = $minrows;} return $rows; } ?>