ser*_*ska 2 javascript vue.js vuejs2
我已经实现了一个组件,它使用 contenteditable="true" 来编辑此 div 上的内容(如文本区域)。
\n\n按照我的代码片段进行操作:
\n\nexport default {\r\n name: \'divArea\',\r\n props: [\'value\'],\r\n mounted() {\r\n this.$el.innerHTML = this.value;\r\n },\r\n methods: {\r\n updateHTML(e) {\r\n const html = e.target.innerHTML;\r\n this.$emit(\'input\', html);\r\n },\r\n },\r\n}Run Code Online (Sandbox Code Playgroud)\r\n<template>\r\n <div contenteditable="true"\r\n v-once\r\n v-html="value"\r\n @input="updateHTML"\r\n @paste="onPaste"\r\n class="txtArea"></div>\r\n</template>Run Code Online (Sandbox Code Playgroud)\r\nI\xe2\x80\x99m 尝试在此区域中实现粘贴功能,以从 html 页面复制内容块,但我希望在粘贴操作后只有文本版本(无 html)。
\n\n目前,我在组件上使用带有 prop 的 v-html 属性,因为我需要在粘贴的文本上添加 html 自定义标记,但前提是用户单击按钮。
\n\n我该怎么做才能实现这种行为?
\n首先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
})
Run Code Online (Sandbox Code Playgroud)
cursor第二部分,如果你想在原来的地方添加粘贴
instead of
e.target.textContent += paste
Run Code Online (Sandbox Code Playgroud)
您可以使用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))
}
Run Code Online (Sandbox Code Playgroud)