这是一个简单的、纯 php 和 html 的解决方案,不需要 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;
}
?>