文本区域的高度在值增加时增加,但在值减小时不会降低

height of textarea increases when value increased but does not reduce when value is decreased

本文关键字:增加 小时 区域 高度 文本      更新时间:2023-09-26
<body>
<script type="text/javascript">$(function(){
$("textarea").live("keyup keydown",function(){var h=$(this);
h.height(h[0].scrollHeight);
});});
</script>
<textarea style="resize:none;width:760px;height:60px; overflow:hidden;" ></textarea>
</body>
当文本区域溢出时,它会得到滚动条和滚动高度,它们被应用于其高度,

但不适用于降低文本区域高度,因为在减小其值长度时,它不会得到滚动条

文本区域的最小滚动高度始终是高度。要获得准确的滚动高度,请先将高度设置为 1。

h.height(1).height(h[0].scrollHeight);

http://jsfiddle.net/aarongloege/t2vAr/

如果你不想自己编码,你也可以使用这个脚本:https://github.com/brandonaaron/jquery-expandable它已经包含一个很好的幻灯片效果;-)

上述代码的纯JavaScript版本

textarea.style.height = '0';
textarea.style.height = textarea.scrollHeight + 'px';