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

如何仅在手动按下dot(.)按键时将其替换为特殊字符“।”,粘贴内容不替换

原有代码问题

原有代码存在两个核心缺陷:

  1. 绑定了全局keyup事件,任意按键抬起都会触发全量替换逻辑,粘贴内容后也会触发该事件,导致粘贴内容中自带的所有点都被替换
  2. 直接对文本框全部内容做替换,会修改历史输入、粘贴内容里的点,不符合仅手动按键替换的需求

修改后完整代码

<!doctype html>
<html dir='ltr' lang='en-GB'>
<head>
  <meta charset="UTF-8">
  <title>test page</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    $(function() {
      $('textarea').on("keydown", function(e) {
        // 仅当按下的按键是英文句号时执行替换逻辑
        if (e.key === '.') {
          // 阻止默认的句号输入
          e.preventDefault();
          const textarea = this;
          const start = textarea.selectionStart;
          const end = textarea.selectionEnd;
          const value = textarea.value;
          // 在当前光标位置插入特殊字符
          textarea.value = value.substring(0, start) + '।' + value.substring(end);
          // 把光标移动到插入的字符后面,保持正常输入体验
          textarea.selectionStart = textarea.selectionEnd = start + 1;
        }
      });
    });
  </script>
</head>
<body>
  <textarea></textarea>
</body>
</html>

实现效果

  • 只有手动按下英文句号按键时才会输出「।」,其他输入场景完全不受影响
  • 粘贴内容中自带的句号不会被替换,历史输入的句号也不会被修改
  • 支持在文本任意位置输入替换,光标位置不会跳转到文本末尾,和普通输入体验一致

内容的提问来源于stack exchange,提问作者Mohammad Suhail

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:06:03