编辑时在textarea输入中添加新行

问题描述

| 我想知道如何在编辑时将新行/行添加到textarea中,即当字母数超过textarea列数时自动添加新行。     

解决方法

        在此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的含义。     ,        您可以使用jQuery AutoResize插件:http://james.padolsey.com/javascript/jquery-plugin-autoresize/     ,        
$(\'textarea\').keyup(function (e) {
    var rows = $(this).val().split(\"\\n\");
    $(this).prop(\'rows\',rows.length);
});
    ,        您可以执行以下操作:
<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”条件下添加一个高度限制。 (不必担心这一点并不引人注目-只是说明要点。)     ,        尝试这个 var txt = $(\“ textarea#idhere \”); txt.val(txt.val()+ \“ \\ n这里的事情\\ n \\ n再次\”);     ,        这是普通的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>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...