提交 cc09bb0c 编写于 作者: W weixin_43814775

Mon Dec 4 22:24:00 CST 2023 inscode

上级 7c434981
......@@ -5,29 +5,11 @@ const formState = reactive<any>({
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;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册