2011-11-29 8 views

答えて

1

何か:

<textarea id="foo" rows="1" cols="40"></textarea> 

$(function() { 

    $("#foo").on("keyup", function() { 

     if ($(this).attr('rows') < 5 && 
      parseInt($(this).val().length/$(this).attr('cols')) >= $(this).attr('rows')) 
      $(this).attr("rows", parseInt($(this).attr("rows"))+1); 

    }); 

}); 

http://jsfiddle.net/Q3pPT/

編集わずかな改善が改行を処理する:

$(function() { 

    $("#foo").on("keyup", function (e) { 

     if ($(this).attr('rows') < 5) 
     { 
      if (
       parseInt($(this).val().length/$(this).attr('cols'))+ 
       ($(this).val().split("\n").length-1) 

       >= 

       $(this).attr('rows') 
      ) 
       $(this).attr("rows", parseInt($(this).attr("rows"))+1); 

      if (e.keyCode == 13) 
      { 
       $(this).attr("rows", parseInt($(this).attr("rows"))+1); 
      } 
     } 

    }); 

}); 

http://jsfiddle.net/Q3pPT/2/

+0

ユーザーがクリックすると入力した場合何?テキストボックスは展開されません。 – codedude

+0

ええ、それは問題だと思います。詳細はこちら:) –

+0

入力を許可してテキストエリアを拡張するのは簡単な修正ですか? – user852974

0

弾性jQのチェックueryプラグイン:http://unwrongest.com/projects/elastic/

CSSのmax-heightプロパティをtextareaのmaxlengthと組み合わせて使用​​すると、5行に制限できます。

0

ダウンロードこのプラグイン:http://james.padolsey.com/demos/plugins/jQuery/autoresize.jquery.js

$('textarea#comment').autoResize({ 
    // On resize: 
    onResize : function() { 
     $(this).css({opacity:0.8}); 
    }, 
    // After resize: 
    animateCallback : function() { 
     $(this).css({opacity:1}); 
    }, 
    // Quite slow animation: 
    animateDuration : 300, 
    // More extra space: 
    extraSpace : 40 
}); 
1

This A List Part articleは最高のこの機能を実装する方法についての深い、ステップバイステップで説明します。

1

私はJake Feaselの答えから考えました。それは、拡張するだけでなく、より少ないコンテンツがある場合のテキスト領域を縮小するためにも働きます。

HTML

<textarea id="foo" rows="1" cols="40"></textarea> 
<div id="stat"></div> 

また、テキストエリアを持っていると、これが必要なsepatate divのコンテンツに応じて必要な行

CSS

​#foo 
{ 
resize:none;   
}​ 

の理想的な数を表示このハンドラを使用してサイズ変更された場合、コードは機能しなくなります。

JS

$(function() { 

    $("#foo").on("keyup", function (e) {  
     var idealRows = parseInt($(this).val().length/$(this).attr('cols'))+ 
       ($(this).val().split("\n").length-1)+1 ; 
     var rows = $(this).attr('rows'); 

     // for the bugging scroll bar 
     if(rows > 4) $('#foo').css('overflow','auto') 
     else $('#foo').css('overflow','hidden') 

     // for expanding and contracting   
     if((idealRows > rows) && (rows < 5) || (idealRows < rows) && (rows > 1)) 
      $(this).attr("rows", idealRows);      

    }); 

});​ 

デモ:それはまた、KeyDownイベントとkeyUpイベントの間でポップアップ表示のスクロールバーの世話をすることhttp://jsfiddle.net/roopunk/xPdaP/3/

注意してください。 IMO:それはまあまあです。

注 ・ホープこのことができます!:)

関連する問題