【发布时间】:2015-07-14 10:27:37
【问题描述】:
我希望能够使用<input> 字段类型的控件,但只允许两行。
目前我正在使用两个字段,但想知道是否有人可以提出一个解决方案来允许输入(类似于 textarea)但不超过两行。我控制字段的宽度等。
作为参考,已加载 Jquery 和 Bootstrap 3。
非常感谢任何帮助。
【问题讨论】:
我希望能够使用<input> 字段类型的控件,但只允许两行。
目前我正在使用两个字段,但想知道是否有人可以提出一个解决方案来允许输入(类似于 textarea)但不超过两行。我控制字段的宽度等。
作为参考,已加载 Jquery 和 Bootstrap 3。
非常感谢任何帮助。
【问题讨论】:
试试这个
var element = document.getElementById('tworows');
make2Lines(element);
function make2Lines(el){
el.setAttribute('rows', 2); // limit height to 2 rows
// el.setAttribute('wrap', 'off'); // ensure no softwrap is not required anymore if we limit the length
el.addEventListener('keydown', limit); // add listener everytime a key is pressed
function limit(e){
if(e.keyCode == 13 && this.value.indexOf('\n')>-1){
// 13 is the ENTER key and \n is the value it make in the textarea
// so if we already have a line break and it's the ENTER key, we prevent it
e.preventDefault();
}
// async to let the dom update before changin the value
setTimeout(limitRow.bind(this), 0);
}
function limitRow(){
var maxLength = 10;
var rows = this.value.split('\n');
rows.forEach(cutOverflow)
this.value = rows.join('\n');
function cutOverflow(row, index, rows) {
rows[index] = row.substring(0, maxLength);
// this if is only if you want to automatically jump to the next line
if (index === 0 && row.length > maxLength)
rows[1] = row.substring(maxLength) + (rows[1] || '');
}
}
}
<textarea id="tworows"></textarea>
短版:function make2Lines(a){function b(a){13==a.keyCode&&this.value.indexOf("\n")>-1&&a.preventDefault(),setTimeout(c.bind(this),0)}function c(){function c(b,c,d){d[c]=b.substring(0,a),0===c&&b.length>a&&(d[1]=b.substring(a)+(d[1]||""))}var a=10,b=this.value.split("\n");b.forEach(c),this.value=b.join("\n")}a.setAttribute("rows",2),a.addEventListener("keydown",b)}
【讨论】:
想到两种方法:
<textarea>,并用一些只允许两行的脚本对其进行扩充。<input> 字段,但设置它们的样式,使它们相互堆叠以创建一个字段的错觉。您可能仍需要一些脚本来处理一些可用性问题,例如按 ENTER 从第一行转到第二行。【讨论】:
如果您在谈论文本太长时换行,根据文档<input type="text"> 无法换行。
但是,如果您正在谈论限制字符长度,则可以使用 maxlength 属性,例如-<input type="text" maxlength="10">
【讨论】:
一个输入字段只能显示一行http://www.w3.org/TR/html-markup/input.text.html#input.text。对于多行,您需要使用 textarea 并设置 rows 属性。如果您需要两个单独的值,您可以在 PHP、Javascript 或其他方式之后完成。
<textarea class="form-control" rows="2">The default text or empty for nothing this is passed as value for this field</textarea>
【讨论】: