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

如何在HTML textarea输入指定字符时自动插入配对字符并调整光标位置

textarea 输入字符自动配对补全解决方案

原实现存在的问题

原有代码仅能在光标位于内容末尾时生效,核心原因是:

  • 依赖endsWith("<")判断整个输入内容的末尾字符,无法识别光标在内容中间输入的<
  • 直接用+=将>拼接到内容末尾,完全忽略光标实际插入位置
  • 未过滤输入事件类型,删除等操作也可能误触发逻辑

修复后实现

HTML 代码

<textarea name="editing" id="editing"></textarea>

JS 代码

const editing = document.querySelector("#editing");

const handler = (event) => {
  // 仅响应用户输入<的场景
  if (event.data !== "<") return;

  // 获取当前光标位置
  const cursorPos = editing.selectionStart;
  const content = editing.value;

  // 可选优化:光标后已存在>则不重复插入
  if (content.charAt(cursorPos) === ">") return;

  // 在光标位置插入配对的>
  editing.value = content.slice(0, cursorPos) + ">" + content.slice(cursorPos);

  // 光标定位到<和>中间
  editing.setSelectionRange(cursorPos, cursorPos);
};

editing.addEventListener("input", handler);
// 兼容低版本IE可保留该监听,现代浏览器无需额外添加
editing.addEventListener("propertychange", handler);

扩展说明

如果需要支持其他配对符号(比如括号、引号等),只需要修改判断条件和插入的对应符号即可,逻辑完全通用。

内容的提问来源于stack exchange,提问作者Siddharth Shyniben

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 04:15:03