const inputVal = ref(''); const isFocused = ref(false); let textareaContext = null; // 获取 textarea 上下文 const getTextareaContext = () => { // #ifdef MP-WEIXIN return new Promise((resolve) => { const query = uni.createSelectorQuery(); query .select('#textarea') .context((res) => { textareaContext = res.context; resolve(res.context); }) .exec(); }); // #endif }; // 焦点事件处理 const onFocus = () => { isFocused.value = true; getTextareaContext(); }; const onBlur = () => { isFocused.value = false; }; // 处理编号逻辑 const handleNumbering = (type, cursorPos) => { // 获取当前行的内容 const lines = inputVal.value.split('\n'); let currentLineIndex = 0; let currentPos = 0; let orderNumber = 1; // 用于有序列表的序号计数 // 找到光标所在行 for (let i = 0; i cursorPos) { currentLineIndex = i; break; } } // 处理编号 const newLines = lines.map((line) => { // 如果是空行,直接返回,不增加序号计数 if (!line.trim()) return line; // 移除已有的编号 line = line.replace(/^(\d+\.|[\*\-])\s*/, '').trim(); if (type === 'ol') { // 有序列表 const numberedLine = `${orderNumber}. ${line}`; orderNumber++; // 只在非空行时增加序号 return numberedLine; } else { // 无序列表 return `* ${line}`; } }); // 更新文本内容 inputVal.value = newLines.join('\n'); // 更新文本内容后的光标处理 nextTick(async () => { const newCursorPos = newLines.slice(0, currentLineIndex + 1).join('\n').length; // #ifdef H5 const textarea = document.querySelector('.respon-textarea'); if (textarea) { textarea.focus(); textarea.setSelectionRange && textarea.setSelectionRange(newCursorPos, newCursorPos); } // #endif // #ifdef MP-WEIXIN try { if (!textareaContext) { await getTextareaContext(); } textareaContext.focus({ success: () => { setTimeout(() => { textareaContext.setSelection({ start: newCursorPos, end: newCursorPos, }); }, 100); }, }); } catch (error) { console.error('设置光标位置失败:', error); } // #endif }); }; 效果图 "https://wmprod.oss-cn-shanghai.aliyuncs.com/community/FvafVXF3LLFtX03jZvJt9GywWOtG.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/community/FvafVXF3LLFtX03jZvJt9GywWOtG.png) "https://wmprod.oss-cn-shanghai.aliyuncs.com/community/FlMMAq-sZL1SdsTdqt1okL9sFaGm.png" (https://wmprod.oss-cn-shanghai.aliyuncs.com/community/FlMMAq-sZL1SdsTdqt1okL9sFaGm.png)