You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现HTML输入框打字时自动左移显示输入内容

解决方案

对于单行<input>输入框实现输入时自动滚动显示内容,按以下方式处理:

  1. 修正CSS样式
    单行input需配合white-space: nowrap才能让overflow-x生效,这也是你之前设置overflow无效的核心原因:
#targetInput {
  width: 300px; /* 自定义输入框宽度 */
  overflow-x: auto;
  white-space: nowrap;
}
  1. 添加JS自动滚动逻辑
    监听输入事件,每次输入后将输入框滚动位置设置为内容总宽度,确保最新输入内容始终可见:
<input type="text" id="targetInput">
<script>
  const input = document.getElementById('targetInput');
  input.addEventListener('input', function() {
    this.scrollLeft = this.scrollWidth;
  });
</script>

若你需要多行输入场景,建议改用<textarea>,其滚动行为更易控制,同样可通过监听input事件设置scrollTop实现自动滚动。

内容的提问来源于stack exchange,提问作者Ali Farhat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 00:13:21