English 中文(简体)
编辑时将新行添加到文本区域输入
原标题:add new row to textarea input while editing

我想知道如何在编辑时向文本区域添加新行,即当字母数超过文本区域的列数时自动添加新行。

最佳回答

一些实现这一点的基本代码,在这个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的含义。

问题回答
$( textarea ).keyup(function (e) {
    var rows = $(this).val().split("
");
    $(this).prop( rows , rows.length);
});

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

你可以这样做:

<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>

如果你愿意的话,你可以在“如果”条件下增加一个高度限制。

(不用担心让这件事变得不引人注目——只是把重点传达出来。)

试试这个

var txt = $("textarea#idhere");
txt.val( txt.val() + " Something here Again");

这是一个普通的JS单行,它自动将文本区域的行数设置为包含的行数:

elt = document.getElementsByTagName( textarea )[0]

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




相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签