gpt4 book ai didi

javascript - 如何在可编辑组件(vue)中的复制/粘贴操作中过滤文本内容

转载 作者:行者123 更新时间:2023-12-01 01:15:12 25 4
gpt4 key购买 nike

我已经实现了一个组件,它使用 contenteditable="true"来编辑此 div 上的内容(如文本区域)。

按照我的代码片段:

export default {
name: 'divArea',
props: ['value'],
mounted() {
this.$el.innerHTML = this.value;
},
methods: {
updateHTML(e) {
const html = e.target.innerHTML;
this.$emit('input', html);
},
},
}
<template>
<div contenteditable="true"
v-once
v-html="value"
@input="updateHTML"
@paste="onPaste"
class="txtArea"></div>
</template>

我正在尝试在此区域中实现粘贴功能,以从 html 页面复制内容 block ,但我希望在粘贴操作后只有文本版本(无 html)。

目前,我在组件上使用带有 prop 的 v-html 属性,因为我需要在粘贴的文本上添加 html 自定义标记,但前提是用户单击按钮。

我该如何实现此行为?

最佳答案

第一个contenteditable是一个真正的魔鬼,我建议不要使用它,但无论如何这是我的解决方案

        let contenteditable = document.querySelector('[contenteditable]')
contenteditable.addEventListener('paste', function(e){
// Prevent the default pasting event and stop bubbling
e.preventDefault()
e.stopPropagation()
// Get the clipboard data
let paste = (e.clipboardData || window.clipboardData).getData('text/plain')

// Do something with paste like remove non-UTF-8 characters
paste = paste.replace(/\x0D/gi, "\n")
e.target.textContent += paste
})

第二部分,如果您想在光标所在位置添加粘贴

  instead of 
e.target.textContent += paste

您可以使用Selection()

       // Find the cursor location or highlighted area
const selection = window.getSelection()
// Cancel the paste operation if the cursor or highlighted area isn't found
// if (!selection.rangeCount) return false
// Paste the modified clipboard content where it was intended to go
if(selection.getRangeAt(0).collapsed){
// TextareaManager.AddToCursor(document.createTextNode(paste))
if(selection.getRangeAt(0).endContainer.nodeName != "DIV"){
selection.getRangeAt(0).insertNode(document.createTextNode(paste))
}else {
e.target.childNodes[0].textContent += paste
}
selection.getRangeAt(0).collapse(false)
}else {
e.target.appendChild(document.createTextNode(paste))
}

关于javascript - 如何在可编辑组件(vue)中的复制/粘贴操作中过滤文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54822753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com