文本框自动扩展

时间:2010-06-02 08:57:14

标签: javascript javascript-events

如何通过javascript使文本框自动扩展

3 个答案:

答案 0 :(得分:0)

我建议使用jQuery这样的javascript库,然后使用像这样的插件:

http://james.padolsey.com/javascript/jquery-plugin-autoresize/

答案 1 :(得分:0)

您可以将值的计数与行* cols进行比较。我真的不知道html中的col中有多少个字母,但是如果你测试过它可以做类似的事情:

var colCount =  document.yourForm.yourTextArea.cols;
var rowCount =  document.yourForm.yourTextArea.rows;
if((colCount * numberOfLettersInACol) * rowCount) <= document.yourForm.yourTextArea.value.length){
    document.yourForm.yourTextArea.rows = rowCount + 1;
}

答案 2 :(得分:0)

给textarea一个ID为“textarea-expand”并试试这个:
注意:删除文本时,这不会“重新收缩” - 它只会扩展为 编辑:(现在没有jquery工作)
http://bit.ly/aOik0B

编辑在线演示
<script type="text/javascript">

// ---------- FitToContent ----------

var maxHeight;

function fitToContent(idSelector) {

 var text = idSelector && idSelector.style ? idSelector : document.getElementById(idSelector);
    if ( !text ) {
      return;
 }

 function adjustHeight(idSelector, maxHeight) {
    var adjustedHeight = text.clientHeight;
    if ( !maxHeight || maxHeight > adjustedHeight ) {
        adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
        if ( maxHeight ) {
           adjustedHeight = Math.min(maxHeight, adjustedHeight);
        }
        if ( adjustedHeight > text.clientHeight ) {
           text.style.height = adjustedHeight + "px";
        }
    }
  }

  adjustHeight(text, document.documentElement.clientHeight);

}

window.onload=function(){
    function init(){
        fitToContent("textarea-expand");
    }
    init();
    document.getElementById("textarea-expand").onkeypress = init
};

</script>
相关问题