【问题标题】:Resize input text field as text is entered输入文本时调整输入文本字段的大小
【发布时间】:2011-07-21 23:29:39
【问题描述】:

是否可以在输入文本时调整文本输入框的大小?我已经在网上搜索过,但没有找到任何东西。

【问题讨论】:

标签: javascript html css


【解决方案1】:

我刚给你做了一个,在这里试试:http://jsfiddle.net/FNMSP/2/

function autoResize(e){
    var ele=e.target;                          //get the text field
    var t=ele.scrollTop;                       //use scroll top to determine if
    ele.scrollTop=0                              //space is enough
    if(t>0){                                       //If it needs more space....
        ele.style.height=(ele.offsetHeight+t+t)+"px";  //Then add space for it!
    }          
}

您可以对文本区域执行此操作,

<textarea onkeydown="autoResize(event)">Auto Resize!</textarea>

或者使用下面的函数将函数附加到每个&lt;textarea&gt;

var ele=document.getElementsByTagName("textarea");
for(i=0;i<ele;i++){
    ele[i].addEventListener("keydown",autoResize,false)
}

请随意使用。

【讨论】:

  • 嗯,在 FF5 中似乎不起作用,我没有看到任何调整大小的东西
  • 删除 CSS 部分中的 overflow-y:hidden 即可。
【解决方案2】:

相当简单但奇怪的实现:)

<script>
function enlarge(ele)
{
   ele.size += 10;
}
</script>

<form>
<input onkeypress="enlarge(this)" size="10"/>
</form>

【讨论】:

  • @mrk... 为什么每次按键都调整大小?
  • 您写了“在键入文本时调整文本输入框的大小” - 因此,在“键入文本时”调用 onkeypress。显然,您需要决定何时或何时不实际调整大小以及调整多少。如果您只想在用户输入数据时调整大小,您可以让 onfocus 和 onblur 处理程序分别放大和缩小尺寸。
【解决方案3】:
<SCRIPT LANGUAGE="JavaScript" type="text/javascript">

  function call_me(max_length) {
      if((document.form1.mybox.value == null ) ||
         (document.form1.mybox.value == "" ))
          document.form1.mybox.size = size;
      if((document.form1.mybox.value.length >= size) &&
         (document.form1.mybox.value.length <= max_length))
          document.form1.mybox.size = document.form1.mybox.value.length + 1;
      else
          document.form1.mybox.size = size;
  }

</script>

LastName: <input type="text" style="font-family: Terminal"
                 name="mybox" maxlength="30" size="10"
                 onFocus="setInterval('call_me(document.form1.mybox.maxLength)', 1)">

<SCRIPT LANGUAGE="JavaScript">

  var size = document.form1.mybox.size; 

</script>

【讨论】:

  • 为什么要将脚本放在大写字母中作为 SCRIPT?为什么使用设置为古老的“javascript”值的语言属性来调用丑陋的向后兼容“功能”?为什么是生活?我把自己交给你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-23
  • 2015-11-01
  • 1970-01-01
相关资源
最近更新 更多