javascript 文本框自动扩展

qlfbtfca  于 2023-01-04  发布在  Java
关注(0)|答案(3)|浏览(145)

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

wsxa1bj1

wsxa1bj11#

你可以将你的值与rows * cols的计数进行比较。我不知道html中一列有多少个字母,但是如果你测试一下,你可以做如下操作:

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;
}
ql3eal8s

ql3eal8s2#

我建议使用javascript库,如jQuery,然后使用这样的插件:
http://james.padolsey.com/javascript/jquery-plugin-autoresize/

x7yiwoj4

x7yiwoj43#

为文本区域指定一个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>

相关问题