简体   繁体   English

通过javascript增加textarea大小

[英]textarea size increase via javascript

JavaScript: JavaScript的:

function x() {
    var value = document.getElementById("test1").value.length;
    if (value <= 18) {
        value.rows = 1;
    } else if (value > 18 && value < 36) {
        value.rows = 2;
    } else if (value > 36 && value < 54) {
        value.rows = 3;
    }
}

HTML: HTML:

<input type="textarea" id="test1" style="overflow:auto" rows="1" cols="18" onkeypress="javascript:x();">

3 questions: 3个问题:

  1. How can I remove these if-else via for or while loop? 如何通过for或while循环删除这些if-else via?
  2. Max size of the field should be 18 but right now it doesnt work exact at 18 even though I made cols="18" . 该字段的最大大小应为18,但即使我使cols="18"它现在也不能在18处完全正常工作。
  3. Is "onkeypress" the best option? “onkeypress”是最好的选择吗? I use the event to delete the value inside a textbox either use delete or backspace which are not part of "keypress". 我使用事件来删除文本框中的值,使用delete或backspace,它们不属于“keypress”。 So basically it doesn't dynamically decrease the rows. 所以基本上它不会动态减少行数。

Textarea is the tag not an attribute value Textarea是标签而不是属性值

<textarea id="test1" style="overflow:auto" rows="1" cols="18">Text goes here</textarea>

For the javascript you are assigning the length to the variable, not the element. 对于javascript,您要为变量分配长度,而不是元素。 So kinda like 有点像

var a = document.getElementById("test1");

a.rows = (a.value.length / 18) + 1;

This is untested code. 这是未经测试的代码。

Only to 1) 仅1)

First you need to set the row to the test1 object not to the value: 首先,您需要将行设置为test1对象而不是值:

document.getElementById("test1").rows = xxx;

Then you did skip the handling for the values of 36 and 54. This should be probably <= 36 and <= 54 . 然后你跳过了处理36和54的值。这可能是<= 36<= 54

Then this: 然后这个:

var textarea = document.getElementById("test1")

if (value == 0) textarea.rows = 1;
else if (value > 54) textarea.rows = 3;
else textarea.rows = Math.floor((value - 1) / 18) + 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM