根据javascript中的文本行数更改textarea的高度 [英] Change height of textarea based on number of lines of text in javascript

查看:385
本文介绍了根据javascript中的文本行数更改textarea的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
使用原型自动调整文本区域

Possible Duplicate:
Autosizing textarea using prototype

如何根据用户放入的文本行数来更改文本区域的高度?

How do I change the height of a text area based on the number of lines of text that the user puts into it?

对于下面的示例,如果用户将文本区域中的文本更改为多行文本,则文本区域将在其自身上放置滚动条,而不是更改其高度以适合行数.

For the example below if the user changed the text in the textarea to more than one line of text then the textarea would put a scroll bar on itself rather than changing its height to fit the number of lines.

<textarea>
This is the default text that will be displayed in the browser. When you change this text and add more lines to it the browser will not change the height of the textarea that this text is in rather it will add a scroll bar, which is not what I want.
<textarea>

推荐答案

<textarea onkeyup="autoSize(this);"></textarea>

function autoSize(ele)
{
   ele.style.height = 'auto';
   var newHeight = (ele.scrollHeight > 32 ? ele.scrollHeight : 32);
   ele.style.height = newHeight.toString() + 'px';
}

将"32"调整为与行高相匹配作为练习.

Adjusting "32" to match line-height is left as an exercise.

这篇关于根据javascript中的文本行数更改textarea的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆