Html 是否可以禁用 textarea 的多行选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10732446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to disable textarea's multiline option?
提问by tesicg
Of course, I can use standard html text box, but I need text area for some reason.
当然,我可以使用标准的 html 文本框,但由于某种原因我需要文本区域。
So, is it possible to disable textarea's multiline option?
那么,是否可以禁用 textarea 的多行选项?
回答by toniedzwiedz
You can set the size of your textarea using the cols
and rows
attributes and make it non-resizable in CSS but you can't prevent the user from adding more than one line. Even if the area is just too small, a scrollbar will appear and let them write as many lines as they want.
您可以使用cols
和rows
属性设置 textarea 的大小并使其在 CSS 中不可调整大小,但您不能阻止用户添加多于一行。即使该区域太小,也会出现一个滚动条,让他们写尽可能多的行。
If you really need to get just one line, I suggest setting the rows
attribute to 1 and checking if the input has a single line with Javascript.
如果你真的只需要一行,我建议将rows
属性设置为 1 并检查输入是否有一行 Javascript。
In html:
在 HTML 中:
<textarea name="a" cols="5" rows="1" ></textarea>
In CSS:
在 CSS 中:
textarea{
resize: none;
#You can use resize: horizontal if you just want to disable vertical resize
}
Still, I'd suggest using an <input type="text" ... />
Why do you want to avoid it?
尽管如此,我还是建议使用<input type="text" ... />
为什么要避免它?
回答by allanlasser
You can keep all the text on a single line by settings rows="1"
on the <textarea>
, like the other answers have suggested, and then applying the following CSS to the text area:
您可以通过rows="1"
上的设置将所有文本保留在一行中<textarea>
,就像其他答案所建议的那样,然后将以下 CSS 应用到文本区域:
resize: none;
white-space: nowrap;
overflow-x: scroll;
This CSS will prevent the single row from wrapping, while still making the keeping the whole line visible by providing a scroll bar to navigate any text that overflows the visible area.
此 CSS 将防止单行换行,同时仍然通过提供滚动条来导航溢出可见区域的任何文本来保持整行可见。
回答by Zlatan
回答by Tikkes
You can set the rows
attribute to 1.
您可以将该rows
属性设置为 1。
It is not possible to disable the multiline
无法禁用多行
回答by Shaikh Amaan FM
Use this pure JS code and it will not allow user to enter multiple lines in textarea
使用这个纯 JS 代码,它不允许用户在 textarea 中输入多行
var textArea = document.getElementsByTagName("textarea")[0];//your desired TextArea
textArea.onkeydown = function (e) {
if (e.keyCode == 13) { e.preventDefault(); }
};
NOTE:This method will not work if user copies a multi line text and pastes it in the TextArea.
注意:如果用户复制多行文本并将其粘贴到 TextArea 中,则此方法将不起作用。
回答by Sandeep
The following jQuery snippet forces textarea to be displayed in a single line.
以下 jQuery 代码片段强制将 textarea 显示在一行中。
$(document).ready(function(){
$('textarea').each(function(){$(this).attr('rows', 1);});
});