提交 ba5d0336 编写于 作者: W weixin_43814775

Tue Dec 5 09:26:00 CST 2023 inscode

上级 cc09bb0c
<script setup lang="ts">
import { ref, reactive, watch, watchEffect, onMounted } from "vue";
const editableDiv = ref<any>(null);
const formState = reactive<any>({
description: "",
});
// 获取可编辑div的innerText内容
const getContent = () => {
return editableDiv.value.innerText;
};
// 设置可编辑div的innerText内容
const setContent = (content: string) => {
if (!editableDiv.value) return;
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(editableDiv.value);
range.collapse(false); // 光标定位到末尾
selection?.removeAllRanges();
selection?.addRange(range);
document.execCommand("insertText", false, content);
};
// 触发描述框 input事件
const handleDescInput = () => {
const result = document.createElement("p");
const content = editableDiv.value.textContent;
const content = getContent();
if (content) {
const result = document.createElement("p");
if (!isComposing) {
for (let i = 0; i < content.length; i++) {
const char = content[i];
......@@ -48,38 +66,28 @@ const handleDescInput = () => {
result.appendChild(document.createTextNode(char));
}
}
}
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);
formState.description = result.innerHTML;
formState.description = result.innerHTML;
} else {
formState.description = "";
}
};
// 添加paste事件监听器,以便处理粘贴
const handleDescPaste = (e) => {
const handleDescPaste = (e: Event) => {
// 阻止默认粘贴行为
e.preventDefault();
// 获取粘贴的纯文本内容
var pastedText = (e.originalEvent || e).clipboardData.getData("text/plain");
const pastedText = (e as ClipboardEvent).clipboardData?.getData("text/plain");
// 在粘贴的文本中插入换行符
pastedText = pastedText.replace(/\s+/g, "\n");
if (pastedText) {
// 在粘贴的文本中插入换行符
const processedText = pastedText.replace(/\s+/g, "\n");
// 将处理后的文本插入可编辑div
document.execCommand("insertText", false, pastedText);
// 将处理后的文本插入可编辑div
setContent(processedText);
}
};
let isComposing = false;
......@@ -106,7 +114,6 @@ const handleCompositionEnd = () => {
@paste="handleDescPaste"
@compositionend="handleCompositionEnd"
@compositionstart="handleCompositionStart"
v-html="formState.description"
></div>
</template>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册