You need to enable JavaScript to run this app. 如何在contenteditable输入框中为每个字符设置不同的letter-spacing字间距
优惠活动
大模型
产品
解决方案
定价
更多

如何在contenteditable输入框中为每个字符设置不同的letter-spacing字间距

可编辑区域单字符独立字间距实现方案

CSS 原生的 letter-spacing 属性只能统一作用于整个文本节点,无法为单个字符设置差异化间距,要实现需求可以按以下方案处理:

核心思路

  • 将输入的每个字符单独用行内标签(如<span>)包裹,为每个标签单独设置间距(可以用letter-spacing,也可以用margin-right,后者兼容性更好)
  • 监听可编辑区域的输入事件,内容变化时自动拆分字符重新渲染,同时处理光标位置避免跳转

完整实现代码

<!DOCTYPE html>
<html>
<head>
  <meta name='viewport' content='initial-scale=1.0' />
  <style>
    #editor {
      white-space: pre-line;
      border: 1px solid #ccc;
      min-height: 50px;
      padding: 8px;
    }
    /* 字符标签的基础样式 */
    .char-item {
      display: inline-block;
    }
  </style>
</head>
<body>
  <div id='editor' contenteditable='true'></div>

  <script>
    const editor = document.getElementById('editor')
    // 自定义每个字符的间距映射表,可根据需求修改
    const getCharSpacing = (char, index) => {
      // 举个例子:奇数位字符间距10px,偶数位2px,可自行调整规则
      return index % 2 === 0 ? '10px' : '2px'
    }

    // 处理输入事件
    editor.addEventListener('input', () => {
      // 保存当前光标位置
      const selection = window.getSelection()
      const cursorOffset = selection.focusOffset

      // 获取纯文本内容
      const text = editor.innerText
      // 清空原有内容,重新拼接每个字符的span标签
      editor.innerHTML = ''
      text.split('').forEach((char, index) => {
        const span = document.createElement('span')
        span.className = 'char-item'
        span.style.marginRight = getCharSpacing(char, index)
        span.innerText = char
        editor.appendChild(span)
      })

      // 恢复光标位置
      const range = document.createRange()
      const childCount = editor.childNodes.length
      if (childCount > 0) {
        const targetOffset = Math.min(cursorOffset, childCount)
        range.setStart(editor.childNodes[targetOffset > 0 ? targetOffset - 1 : 0], targetOffset > 0 ? 1 : 0)
        range.collapse(true)
        selection.removeAllRanges()
        selection.addRange(range)
      }
    })
  </script>
</body>
</html>

自定义调整说明

  • 如果你需要为特定字符设置固定间距,只需修改getCharSpacing函数的返回规则即可,比如判断字符内容返回对应间距值
  • 如果不需要margin-right,也可以替换为style.letterSpacing设置,效果一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 15:00:00