javascript 使用 contentEditable div 而不是 textarea 有什么缺点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5284193/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:38:33  来源:igfitidea点击:

What are the cons of using a contentEditable div rather than a textarea?

javascripthtmlcsscontenteditable

提问by Babiker

Would I be shooting myself in the foot by using a div with attribute contentEditable="true"as a text field rather than a textarea?

我会通过使用带有属性的 divcontentEditable="true"作为文本字段而不是文本区域来射击自己吗?

采纳答案by TML

It would work fine, but it'd be a little bit more difficult than a form, simply because you're going to have to wire up your own logic to make the button's click event track down the correct div, get its content, and then perform the submission. The advantage of a textarea is that the browser takes care of all that for you.

它会工作得很好,但它比表单要困难一点,仅仅是因为您将不得不连接自己的逻辑以使按钮的点击事件跟踪正确的 div,获取其内容,然后然后执行提交。textarea 的优点是浏览器会为您处理所有这些。

回答by florian

It's not the same thing. First semantically, the purpose of a textarea is to write/edit plain text whereas with contentEditable you can edit list for instance (see: htmldemo) Second the behavior is also different. For example, in chrome when you test the link below and that you delete all the content you loose the focus (the div element disappear) which is not the expected behavior, or if it is it's idiot.

这不是一回事。首先在语义上,textarea 的目的是编写/编辑纯文本,而使用 contentEditable,您可以编辑列表,例如(参见:htmldemo)其次,行为也不同。例如,在 chrome 中,当您测试下面的链接并删除所有内容时,您会失去焦点(div 元素消失),这不是预期的行为,或者是白痴。

回答by LeOn - Han Li

The Gmail's mail edit box is also a divwith contenteditable="true". The major benefit is it has auto-adjustheight as user input text/content. Also it supports rich textinside. You can mimic the Textareaby setting a max height if need.

Gmail的邮件编辑框也divcontenteditable="true"。主要好处是它具有作为用户输入文本/内容的自动调整高度。它还支持里面的富文本Textarea如果需要,您可以通过设置最大高度来模拟。

On the other hand if you want auto height in Textarea, you might have to use js to bind some listener to the oninputhook.

另一方面,如果您想要自动高度Textarea,您可能必须使用 js 将一些侦听器绑定到oninput钩子。