如何让input field中文本达边界后自动换行而非横向扩展?
实现输入框文本自动换行(替代textarea方案)
原生<input>是单行输入控件,本身不支持文本自动换行。如果不想用<textarea>,可以通过contenteditable元素模拟输入框,实现需求:
- 代码实现
<div class="custom-input" contenteditable="true" placeholder="请输入内容"></div> <style> .custom-input { border: 1px solid #ddd; border-radius: 4px; padding: 8px 10px; width: 300px; /* 固定宽度触发换行 */ min-height: 40px; font-size: 14px; font-family: system-ui, sans-serif; /* 核心换行属性 */ white-space: pre-wrap; word-wrap: break-word; } /* 模拟placeholder效果 */ .custom-input:empty:before { content: attr(placeholder); color: #999; } /* 聚焦样式优化 */ .custom-input:focus { outline: none; border-color: #2563eb; box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2); } </style>
- 关键说明
white-space: pre-wrap:保留输入的空格,同时允许文本在容器边界自动换行word-wrap: break-word:处理超长单词,避免超出容器范围- 若需要配合表单提交,可通过JavaScript将
custom-input的textContent同步到隐藏的<input>元素中
内容的提问来源于stack exchange,提问作者popsmoke
相关产品推荐
相关产品推荐

