Dynamically increasing textbox height? [duplicate]

Deadly 提交于 2019-12-12 18:19:18

问题


Possible Duplicate:
Autosizing Textarea

Hello all, I am trying to solve a problem and getting absolutely no where with it. What I am trying to do is dynamically change the height of an inputbox when the users text overflows it's width (sorta like Facebook's status update textbox).

You enter a brief update, and if the text is longer than the textbox, it creates a new row. I tried using a textarea, but for whatever reason cannot force it to be exactly 1 row by default.

Anyone know an easy way of doing this? :(


回答1:


You can manually control the size of the textarea using the CSS height and width parameters. By binding a keypress event to the textarea, you can get the amount of text in the box and adjust the height accordingly. For example, here's some jQuery that will add 20 pixels to the height of the box for every 50 characters you put in:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>

<textarea id="textbox" style="height:20px;width:400px;"></textarea>

<script type="text/javascript">
$(document).ready(function() {
    $("#textbox").val('');
    $("#textbox").keypress(function() {
        var textLength = $("#textbox").val().length;
        if (textLength % 50 == 0) {
            var height = textLength/50;
            $("#textbox").css('height', 20+(height*20));
        }
    });
});
</script>

You can tweak the values to get the desired effect.




回答2:


To get the textarea to stretch, give this a go (jQuery): http://www.unwrongest.com/projects/elastic/.

As for the height of exactly one row, you could try rows="1" in the <textarea> tag, as well as removing CSS styling. Some browsers, however, may set a textarea's minimum height to more than one row.

Another solution would be to use a div on screen that, when the user clicks on it, makes the browser focus on a hidden textbox. The user types into the hidden text box, and the div is given the textbox's contents via. JavaScript. The tricky bit then is getting the flashing cursor, but you could use the pipe | character in the div and make it flash, although this starts getting long winded about the time you start it. I'd try with the textarea again personally :-)

Hope this helps,

James



来源:https://stackoverflow.com/questions/4422043/dynamically-increasing-textbox-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!