编辑时将新行添加到textarea输入

时间:2011-06-01 07:40:05

标签: javascript jquery html

我想知道如何在编辑时向textarea添加新的行/行,即当字母数超过textarea的cols数时自动添加新行。

6 个答案:

答案 0 :(得分:2)

您可以使用jQuery AutoResize插件:http://james.padolsey.com/javascript/jquery-plugin-autoresize/

答案 1 :(得分:2)

实现此目的的一些基本代码,在此jsfiddle(http://jsfiddle.net/NZbZn/)中进行了测试。显然,它需要工作,但显示了基本概念。

jQuery(document).ready(function(){

    //after typing occurs
    jQuery('textarea#expander').keyup(function(){

        //figure out how many chars
        var length = jQuery(this).val().length;

        //if more than 10
        if(length > 10){

            //if the modulus 10 of the length is zero, there are a multiple of 10 chars, so we need to extend by a row
            //(NOTE the obvious problem - this will expand while deleting chars too!)
            if((length % 10) == 0){

                //figure out the number of rows, increment by one, and reset rows attrib
                var rows = jQuery(this).attr('rows');
                rows++;

                jQuery(this).attr('rows', rows);    
            }  
        }   
    });    
});

再次,首先考虑UI含义。

答案 2 :(得分:2)

$('textarea').keyup(function (e) {
    var rows = $(this).val().split("\n");
    $(this).prop('rows', rows.length);
});

答案 3 :(得分:1)

你可以这样做:

<textarea id="ta" onkeyup="checkScroll(this)" style="height:4em; overflow:auto">
asdf
</textarea>

<script>
function checkScroll(obj) { 
  if(obj.clientHeight < obj.scrollHeight) {
    obj.style.height = (parseInt(obj.style.height)+1) + 'em';
  }
}
</script>

如果您愿意,可以在“if”条件中添加高度限制。

(不用担心让这个不引人注目 - 只是明白了。)

答案 4 :(得分:0)

试试这个

var txt = $(“textarea#idhere”);
txt.val(txt.val()+“\ nSomething here \ n \ nAgain”);

答案 5 :(得分:0)

这是普通的JS one衬纸,它可以自动将textarea的行数设置为其包含的行数:

elt = document.getElementsByTagName('textarea')[0]

elt.addEventListener('keyup',()=>elt.setAttribute('rows',elt.value.split('\n').length))
<textarea rows='1'>Type some lines!</textarea>

相关问题