我们写的时候如何自动扩展textarea

时间:2011-08-16 11:40:35

标签: javascript css textarea expand

如何在写作时自动扩展文本区域?

这是我的代码:

<script type="text/javascript">
                function clearContents(element) {
                  element.value = '';
                }
                function updateContents(element) {
                  element.value = "What's on your mind?";
                }
            </script>
            <h1>New status</h1>
            <form action="index.php" method="post" name="new_message">
                <textarea id="message" onFocus="clearContents(this);" onKeyPress="catchEnter(this);">What's on your mind?</textarea>
                <input type="button" value="Post"> 
            </form>

2 个答案:

答案 0 :(得分:3)

我一直在使用elastic textbox from Unwrongest,这是一个非常棒的插件。

只需包含该插件,然后使用以下命令调用该插件:

$('#TextAreaId').elastic();

就是这样。

在此处查看演示:http://jsfiddle.net/janjarfalk/r3Ekw/

<小时/> 如何通过3个步骤实现这一目标:

第1步:将其添加到html中的<head>

http://jquery-elastic.googlecode.com/svn/trunk/jquery.elastic.source.js

第2步:在</body>标记之前将其添加到您的html文件中:

$('textarea').elastic();

第3步:仅在步骤2之后无效后才使用此步骤。在步骤1中添加代码上方的下一行:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>

你完成了。如果您已经有jQuery,请跳过第3步。

答案 1 :(得分:0)

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

<script>
function textarea(box){
box.style.height = box.scrollHeight+'px';
}
</script>

然后Bam !!!你有一个成长的textarea。您可能需要考虑边框和填充。包括函数中的那些。