基于 contenteditable 实现变量插入富文本编辑器

news2026/4/27 19:57:57
目录第一章 前言第二章 实现2.1 组件功能概览2.2 实现思路2.2.1 富文本核心contenteditable2.2.2 标签解析与序列化2.2.3 光标定位与弹窗跟随2.3.4 中文输入法兼容处理2.3.5 Teleport 解决层级问题2.3.6 双向绑定防死循环机制第三章 完整代码第一章 前言在目前的很多AI系统后台管理系统、表单模板配置、消息推送、问卷系统等业务中我们经常需要实现一类通用需求在输入框中输入 / 或者 唤起变量列表→ 选择变量自动插入为标签 → 支持删除标签 → 数据双向绑定 → 支持回显与编辑。本文基于 Vue3 原生 DOM API实现一套轻量、无第三方依赖。第二章 实现2.1 组件功能概览本组件已实现的完整能力v-model 双向绑定数据格式为{{id|name}}输入/自动触发变量选择面板支持关键词模糊搜索过滤变量列表光标实时定位弹窗跟随光标位置键盘 ↑↓ 选择、Enter 确认、ESC 关闭插入不可编辑标签标签支持删除支持 placeholder、禁用状态、聚焦样式粘贴自动过滤为纯文本防止富文本污染兼容中文输入法composition 事件处理使用 Teleport 挂载弹窗到 body解决层级遮挡支持外部通过ref.focus()主动聚焦数据存储格式示例测试描述{{22bb83a1e45b4f1ea0db456a87eb842e|机构性质}} {{436979cd47234041adbbb22285cb9b81|测试印章2}} {{8a5e203679a7486f99327ca7ef75a869|机构地址}} 2.2 实现思路2.2.1 富文本核心contenteditablecontenteditable 是 HTML 提供的一个非常强大的属性它能瞬间把任何元素变成一个可编辑区域。借助它我们可以轻松实现在线笔记、表格编辑、富文本编辑器等功能。div refeditorRef classmention-textarea__editor :contenteditable!disabled /divcontenteditabletrue让普通 div 变成浏览器原生可编辑区域优点轻量、可控、不依赖任何富文本库难点光标管理、DOM 序列化、数据同步2.2.2 标签解析与序列化这是整个功能最核心的逻辑实现 字符串 ↔ DOM 互相转换匹配格式{{变量ID|变量名}}const TAG_REGEX /\{\{([^|])\|([^}])\}\}/g字符串 → DOM 片段function parseToSegments(str) { // 拆分文本片段与标签片段 }DOM 片段 → 可存储字符串function serializeFromDOM(el) { // 遍历 DOM 节点还原为 {{id|name}} 格式 }作用编辑时DOM 结构 → 字符串用于提交后端回显时字符串 → DOM 结构用于页面渲染2.2.3 光标定位与弹窗跟随function getCaretRect() { const sel window.getSelection() const range sel.getRangeAt(0) return range.getBoundingClientRect() }window.getSelection()获取用户选区对象getRangeAt(0)获取光标范围getClientRects()获取光标坐标零宽字符 \u200b 兼容空行光标位置获取2.3.4 中文输入法兼容处理const isComposing ref(false) function handleCompositionStart() { isComposing.value true } function handleCompositionEnd() { isComposing.value false handleInput() }监听 compositionstart / compositionend 避免中文输入未上屏时触发搜索、校验、弹窗2.3.5 Teleport 解决层级问题Teleport tobody div classmention-popup :stylepopupAbsStyle ... /div /Teleport2.3.6 双向绑定防死循环机制let skipNextWatch false function emitValue() { skipNextWatch true // ... 触发更新 } watch(() props.modelValue, (newVal) { if (skipNextWatch) { skipNextWatch false return } // ... 重新渲染 })自身触发更新时跳过监听避免无限循环外部修改 modelValue 时正常响应并重新渲染第三章 完整代码script setup import { ref, computed, watch, nextTick, onMounted, onUnmounted, throttle, debounce } from vue const props defineProps({ modelValue: { type: String, default: }, mentionOptions: { type: Array, default: () [] }, placeholder: { type: String, default: 请输入内容输入 / 可插入变量 }, disabled: { type: Boolean, default: false } }) const emit defineEmits([update:modelValue]) const editorRef ref(null) const showPopup ref(false) const popupStyle ref({ top: 0px, left: 0px }) const searchText ref() const selectedIndex ref(0) const slashInfo ref(null) const isFocused ref(false) const isComposing ref(false) // 用于清理标签关闭事件防止内存泄漏 const tagClickHandlers new WeakMap() const filteredOptions computed(() { if (!searchText.value) return props.mentionOptions const keyword searchText.value.toLowerCase() return props.mentionOptions.filter(opt opt.name.toLowerCase().includes(keyword) ) }) watch(filteredOptions, () { selectedIndex.value 0 }) const TAG_REGEX /\{\{([^|])\|([^}])\}\}/g // 字符串解析为片段 function parseToSegments(str) { if (!str) return [] const segments [] let lastIndex 0 const re new RegExp(TAG_REGEX.source, g) let match while ((match re.exec(str)) ! null) { if (match.index lastIndex) { segments.push({ type: text, value: str.slice(lastIndex, match.index) }) } segments.push({ type: tag, id: match[1], name: match[2] }) lastIndex re.lastIndex } if (lastIndex str.length) { segments.push({ type: text, value: str.slice(lastIndex) }) } return segments } // DOM 序列化为存储字符串 function serializeFromDOM(el) { if (!el) return let result for (const node of el.childNodes) { if (node.nodeType Node.TEXT_NODE) { result node.textContent } else if (node.nodeType Node.ELEMENT_NODE) { if (node.dataset?.tagId) { result {{${node.dataset.tagId}|${node.dataset.tagName}}} } else { result node.textContent || } } } return result } // 创建标签 DOM function createTagNode(id, name) { const span document.createElement(span) span.className mention-tag span.contentEditable false span.dataset.tagId id span.dataset.tagName name const label document.createElement(span) label.className mention-tag__label label.textContent name span.appendChild(label) const close document.createElement(span) close.className mention-tag__close close.textContent \u00d7 const handler (e) { e.preventDefault() e.stopPropagation() span.remove() emitValue() } close.addEventListener(mousedown, handler) tagClickHandlers.set(close, handler) span.appendChild(close) return span } // 渲染编辑器内容 function renderDOM() { const el editorRef.value if (!el) return const segments parseToSegments(props.modelValue) el.innerHTML segments.forEach(seg { if (seg.type text) { el.appendChild(document.createTextNode(seg.value)) } else { el.appendChild(createTagNode(seg.id, seg.name)) } }) } // 获取光标位置 function getCaretRect() { const sel window.getSelection() if (!sel || !sel.rangeCount) return null const range sel.getRangeAt(0).cloneRange() range.collapse(true) const rect range.getClientRects()[0] if (rect) return rect // 兼容空光标位置 const span document.createElement(span) span.textContent \u200b range.insertNode(span) const r span.getBoundingClientRect() span.remove() sel.removeAllRanges() sel.addRange(range) return r } // 节流更新弹窗位置 const updatePopupPositionThrottle throttle(() { const rect getCaretRect() const editorRect editorRef.value?.getBoundingClientRect() if (!rect || !editorRect) return popupStyle.value { top: ${rect.bottom - editorRect.top 4}px, left: ${rect.left - editorRect.left}px } }, 80) // 关闭弹窗 function closePopup() { showPopup.value false searchText.value slashInfo.value null selectedIndex.value 0 } // 输入事件防抖 const handleInputDebounce debounce(() { if (isComposing.value) return checkSlashTrigger() emitValue() }, 180) // 中文输入开始 function handleCompositionStart() { isComposing.value true } // 中文输入结束 function handleCompositionEnd() { isComposing.value false handleInputDebounce() } // 检测 / 触发变量面板 function checkSlashTrigger() { const sel window.getSelection() if (!sel || !sel.rangeCount) { closePopup() return } const range sel.getRangeAt(0) const node range.startContainer if (node.nodeType ! Node.TEXT_NODE) { closePopup() return } const text node.textContent const cursor range.startOffset const slashIdx text.lastIndexOf(/, cursor) if (slashIdx -1 || slashIdx cursor) { closePopup() return } const between text.slice(slashIdx 1, cursor) if (/\n/.test(between)) { closePopup() return } searchText.value between slashInfo.value { node, slashOffset: slashIdx } selectedIndex.value 0 showPopup.value true nextTick(updatePopupPositionThrottle) } // 选择变量插入 function selectOption(opt) { if (!slashInfo.value || !editorRef.value) return const { node, slashOffset } slashInfo.value const sel window.getSelection() const text node.textContent const before text.slice(0, slashOffset) const after text.slice(sel.getRangeAt(0).startOffset) const parent node.parentNode parent.insertBefore(document.createTextNode(before), node) parent.insertBefore(createTagNode(opt.id, opt.name), node) parent.insertBefore(document.createTextNode(after || \u00a0), node) parent.removeChild(node) closePopup() emitValue() } // 键盘上下选择 function handleKeydown(e) { if (!showPopup.value) return const opts filteredOptions.value if (e.key ArrowDown) { e.preventDefault() selectedIndex.value (selectedIndex.value 1) % opts.length } else if (e.key ArrowUp) { e.preventDefault() selectedIndex.value (selectedIndex.value - 1 opts.length) % opts.length } else if (e.key Enter) { e.preventDefault() opts.length selectOption(opts[selectedIndex.value]) } else if (e.key Escape) { e.preventDefault() closePopup() } } function handleFocus() { isFocused.value true } function handleBlur() { isFocused.value false setTimeout(closePopup, 200) } // 粘贴纯文本替换废弃 API function handlePaste(e) { e.preventDefault() const text e.clipboardData.getData(text/plain) const range window.getSelection().getRangeAt(0) range.deleteContents() range.insertNode(document.createTextNode(text)) emitValue() } // 弹窗样式 const popupAbsStyle computed(() { const rect editorRef.value?.getBoundingClientRect() if (!rect) return {} return { position: fixed, top: ${rect.top parseFloat(popupStyle.value.top || 0)}px, left: ${rect.left parseFloat(popupStyle.value.left || 0)}px, zIndex: 9999 } }) // 双向绑定防死循环 let skipNextWatch false function emitValue() { skipNextWatch true const val serializeFromDOM(editorRef.value) if (val ! props.modelValue) { emit(update:modelValue, val) } if (!val editorRef.value) { nextTick(() { editorRef.value.innerHTML }) } } watch( () props.modelValue, (newVal) { if (skipNextWatch) { skipNextWatch false return } const current serializeFromDOM(editorRef.value) if (current ! newVal) { renderDOM() } } ) onMounted(() { renderDOM() }) // 销毁事件避免内存泄漏 onUnmounted(() { tagClickHandlers.forEach((handler, el) { el.removeEventListener(mousedown, handler) }) }) defineExpose({ focus: () editorRef.value?.focus() }) /script template div classmention-textarea :class{ is-focused: isFocused, is-disabled: disabled } div refeditorRef classmention-textarea__editor :contenteditable!disabled :data-placeholderplaceholder inputhandleInputDebounce keydownhandleKeydown focushandleFocus blurhandleBlur pastehandlePaste compositionstarthandleCompositionStart compositionendhandleCompositionEnd /div Teleport tobody div v-ifshowPopup filteredOptions.length classmention-popup :stylepopupAbsStyle div v-for(opt, idx) in filteredOptions :keyopt.id classmention-popup__item :class{ is-active: idx selectedIndex } mousedown.preventselectOption(opt) mouseenterselectedIndex idx {{ opt.name }} /div /div /Teleport /div /template style langscss scoped .mention-textarea { position: relative; border: 1px solid #dcdfe6; border-radius: 4px; background: #fff; transition: border-color 0.2s; width: 100%; .is-focused { border-color: #605ce5; } .is-disabled { background: #f5f7fa; cursor: not-allowed; .mention-textarea__editor { cursor: not-allowed; color: #a8abb2; } } __editor { min-height: 60px; max-height: 200px; overflow-y: auto; padding: 5px 14px; font-size: 14px; line-height: 1.8; color: #606266; outline: none; word-break: break-all; white-space: pre-wrap; :empty::before { content: attr(data-placeholder); color: #c9c9c9; pointer-events: none; } } } /style style langscss .mention-tag { display: inline-flex; align-items: center; gap: 2px; padding: 0 8px; margin: 0 2px; height: 22px; line-height: 22px; background: rgba(96, 92, 229, 0.08); border: 1px solid #605ce5; border-radius: 4px; color: #605ce5; font-size: 12px; vertical-align: middle; user-select: none; cursor: default; __label { max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } __close { cursor: pointer; font-size: 14px; line-height: 1; margin-left: 2px; color: #605ce5; opacity: 0.6; :hover { opacity: 1; } } } .mention-popup { background: #fff; border: 1px solid #e4e7ed; border-radius: 4px; box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12); max-height: 200px; overflow-y: auto; min-width: 150px; __item { padding: 8px 12px; font-size: 14px; color: #606266; cursor: pointer; transition: background 0.15s; :hover, .is-active { background: #f5f4fe; color: #605ce5; } } } /style

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2560505.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…

wordpress后台更新后 前端没变化的解决方法

使用siteground主机的wordpress网站,会出现更新了网站内容和修改了php模板文件、js文件、css文件、图片文件后,网站没有变化的情况。 不熟悉siteground主机的新手,遇到这个问题,就很抓狂,明明是哪都没操作错误&#x…

网络编程(Modbus进阶)

思维导图 Modbus RTU(先学一点理论) 概念 Modbus RTU 是工业自动化领域 最广泛应用的串行通信协议,由 Modicon 公司(现施耐德电气)于 1979 年推出。它以 高效率、强健性、易实现的特点成为工业控制系统的通信标准。 包…

UE5 学习系列(二)用户操作界面及介绍

这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…

IDEA运行Tomcat出现乱码问题解决汇总

最近正值期末周,有很多同学在写期末Java web作业时,运行tomcat出现乱码问题,经过多次解决与研究,我做了如下整理: 原因: IDEA本身编码与tomcat的编码与Windows编码不同导致,Windows 系统控制台…

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…

XML Group端口详解

在XML数据映射过程中&#xff0c;经常需要对数据进行分组聚合操作。例如&#xff0c;当处理包含多个物料明细的XML文件时&#xff0c;可能需要将相同物料号的明细归为一组&#xff0c;或对相同物料号的数量进行求和计算。传统实现方式通常需要编写脚本代码&#xff0c;增加了开…

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器的上位机配置操作说明

LBE-LEX系列工业语音播放器|预警播报器|喇叭蜂鸣器专为工业环境精心打造&#xff0c;完美适配AGV和无人叉车。同时&#xff0c;集成以太网与语音合成技术&#xff0c;为各类高级系统&#xff08;如MES、调度系统、库位管理、立库等&#xff09;提供高效便捷的语音交互体验。 L…

(LeetCode 每日一题) 3442. 奇偶频次间的最大差值 I (哈希、字符串)

题目&#xff1a;3442. 奇偶频次间的最大差值 I 思路 &#xff1a;哈希&#xff0c;时间复杂度0(n)。 用哈希表来记录每个字符串中字符的分布情况&#xff0c;哈希表这里用数组即可实现。 C版本&#xff1a; class Solution { public:int maxDifference(string s) {int a[26]…

【大模型RAG】拍照搜题技术架构速览:三层管道、两级检索、兜底大模型

摘要 拍照搜题系统采用“三层管道&#xff08;多模态 OCR → 语义检索 → 答案渲染&#xff09;、两级检索&#xff08;倒排 BM25 向量 HNSW&#xff09;并以大语言模型兜底”的整体框架&#xff1a; 多模态 OCR 层 将题目图片经过超分、去噪、倾斜校正后&#xff0c;分别用…

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…

接口测试中缓存处理策略

在接口测试中&#xff0c;缓存处理策略是一个关键环节&#xff0c;直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性&#xff0c;避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明&#xff1a; 一、缓存处理的核…

龙虎榜——20250610

上证指数放量收阴线&#xff0c;个股多数下跌&#xff0c;盘中受消息影响大幅波动。 深证指数放量收阴线形成顶分型&#xff0c;指数短线有调整的需求&#xff0c;大概需要一两天。 2025年6月10日龙虎榜行业方向分析 1. 金融科技 代表标的&#xff1a;御银股份、雄帝科技 驱动…

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…

Linux应用开发之网络套接字编程(实例篇)

服务端与客户端单连接 服务端代码 #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <pthread.h> …

华为云AI开发平台ModelArts

华为云ModelArts&#xff1a;重塑AI开发流程的“智能引擎”与“创新加速器”&#xff01; 在人工智能浪潮席卷全球的2025年&#xff0c;企业拥抱AI的意愿空前高涨&#xff0c;但技术门槛高、流程复杂、资源投入巨大的现实&#xff0c;却让许多创新构想止步于实验室。数据科学家…

深度学习在微纳光子学中的应用

深度学习在微纳光子学中的主要应用方向 深度学习与微纳光子学的结合主要集中在以下几个方向&#xff1a; 逆向设计 通过神经网络快速预测微纳结构的光学响应&#xff0c;替代传统耗时的数值模拟方法。例如设计超表面、光子晶体等结构。 特征提取与优化 从复杂的光学数据中自…