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

解决同容器双span文本重叠问题:实现输入与补全文本并排

解决可编辑span与补全建议span重叠问题

问题核心是两个span都使用了完全相同的绝对定位规则,导致元素重叠;同时绝对定位脱离文档流,补全span无法感知输入span的宽度变化,自然无法跟随在输入内容后方。以下是具体解决方案:

调整CSS布局

修改后的CSS代码解决了定位冲突,让补全文本自动跟随输入内容:

<style scoped>
   .pad-container {
       padding: 0;
       width: 640px;
       border-radius: 12px;
       border: medium solid;
       border-color: #0072c6;
   }
  .divAutocomplete {
       font-family: "Crete Round";
       font-size: 16px;
       border-radius: 8px;
       height: 32px;
       width: 100%;
       display: flex;
       align-items: center;
       padding-left: 8px;
       background-color: hwb(244 16% 17% / 0.1);
       caret-color: #0072c6;
       color: #0072c6;
   }
  span {
       display: inline-block;
       min-width: 1px;
       outline: none;
       white-space: nowrap;
   }
 .editable {
       text-transform: lowercase;
       width: auto;
       margin-right: 8px;
   }
 .placeholder {
       color: gray;
       pointer-events: none;
   }
</style>

优化光标定位逻辑(可选)

改为flex布局后,建议调整setCaret方法,确保光标始终停在输入内容末尾:

methods: {
  setCaret() {
    const editableSpan = this.$refs.editbar;
    if (!editableSpan) return;
    const range = document.createRange();
    const selection = window.getSelection();
    range.selectNodeContents(editableSpan);
    range.collapse(false);
    selection.removeAllRanges();
    selection.addRange(range);
    editableSpan.focus();
  },
  // 保留原有sendText、preventInput方法
}

修改说明

  1. 父容器.divAutocomplete改用flex布局,实现内部元素横向排列+垂直居中,用容器内边距替代原span的left定位
  2. 移除两个span的绝对定位,改用inline-block让元素处于正常文档流,补全span会自动跟随输入span的宽度变化
  3. 给.editable添加右边距,确保输入内容和补全建议保持固定间距
  4. 给.placeholder设置pointer-events: none,避免用户误触发补全文本区域的交互
  5. 修复原CSS中多余的逗号(会导致样式解析错误)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 13:50:29