2011-06-01 18 views
1

我不知道如何將新的行/行添加到textarea的同時編輯時的字母數超過文字區域的cols的數量自動添加新行即到。添加新行到textarea的輸入,同時編輯

+2

說實話,我不會。你什麼時候停止添加新行? 5點以後? 10?當它佔用了一半的頁面?我建議你設置一個合理的寬度和高度,並允許textarea按照用戶預期的那樣實現滾動。 但是,如果你對此設置並有一個很好的理由,那麼它應該是一個非常簡單的問題,通過textarea的keyup事件或類似的方法來標記字符數,並在需要時更改rows屬性。 – dartacus 2011-06-01 07:46:50

+0

另請注意,較新的瀏覽器(FF4,Chrome)允許通過拖動右下角來調整文本區域的大小。 – Xion 2011-06-01 07:48:38

+0

啊哈,但我不希望用戶控制textarea的大小,此外我不希望他滾動只是做他的評論和感覺everty事情是好的,而他編輯 – sam 2011-06-01 07:59:48

回答

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的含義。

+0

非常感謝:)我採取了jquery插件它修改後幫助了很多:) – sam 2011-06-01 08:10:08

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> 

如果你想,你可以在「如果」條件添加一個高度限制。

(不擔心做這個不顯眼 - 對面獲取點)

0

試試這個

VAR的txt = $( 「#textarea的idhere」);
txt.val(txt.val()+「\ n這裏有些東西\ n \ nAgain」);

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