diff --git a/src/components/HelloWorld.vue b/src/components/HelloWorld.vue index 6bb4bf3a9304c68a62fcd641535be91b2c655507..cff056fd130a767e1e90ffbd4bae17c91aff869a 100644 --- a/src/components/HelloWorld.vue +++ b/src/components/HelloWorld.vue @@ -5,29 +5,11 @@ const formState = reactive({ description: "", }); -// 保存光标位置 -let savedSelection: Selection | null = null; - -// 获取当前光标位置的 Range 对象 -const getCurrentRange = () => { - const selection = window.getSelection(); - if (selection && selection.rangeCount > 0) { - return selection.getRangeAt(0); - } - return null; -}; - -// 恢复光标位置 -const restoreSelection = () => { - if (savedSelection) { - const selection = window.getSelection(); - selection.removeAllRanges(); - selection.addRange(savedSelection); - } -}; - -// 触发描述框 input 事件 +// 触发描述框 input事件 const handleDescInput = () => { + + + const result = document.createElement("p"); const content = editableDiv.value.textContent; @@ -50,12 +32,12 @@ const handleDescInput = () => { } if (hashtag.length > 1) { - // 创建 span 元素并设置样式和内容 + // 创建span元素并设置样式和内容 var span = document.createElement("span"); span.className = "hashtag"; span.innerText = hashtag; console.log("hashtag", hashtag); - // 将 span 元素添加到可编辑 div 中 + // 将span元素添加到可编辑div中 result.appendChild(span); } else { result.appendChild(document.createTextNode(char)); @@ -67,15 +49,26 @@ const handleDescInput = () => { } } } + editableDiv.value.focus(); +var range = document.createRange(); +range.selectNodeContents(editableDiv.value); +range.collapse(false); +var sel = window.getSelection(); +console.log('111',sel.anchorOffset) +//判断光标位置,如不需要可删除 +if(sel.anchorOffset!=0){ + console.log('会来到这里') + formState.description = result.innerHTML; + +return; +}; +sel.removeAllRanges(); +sel.addRange(range); - // 保存当前光标位置 - savedSelection = getCurrentRange(); formState.description = result.innerHTML; - // 恢复光标位置 - restoreSelection(); }; -// 添加 paste 事件监听器,以便处理粘贴 +// 添加paste事件监听器,以便处理粘贴 const handleDescPaste = (e) => { // 阻止默认粘贴行为 e.preventDefault(); @@ -85,12 +78,8 @@ const handleDescPaste = (e) => { // 在粘贴的文本中插入换行符 pastedText = pastedText.replace(/\s+/g, "\n"); - // 保存当前光标位置 - savedSelection = getCurrentRange(); - // 将处理后的文本插入可编辑 div + // 将处理后的文本插入可编辑div document.execCommand("insertText", false, pastedText); - // 恢复光标位置 - restoreSelection(); }; let isComposing = false;