javascript - 如何在可编辑组件(vue)中的复制/粘贴操作中过滤文本内容
问题描述
我已经实现了一个组件,它使用 contenteditable="true" 来获得在这个 div 上编辑内容的可能性(如 textarea)。
按照我的代码片段:
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 页面复制内容块,但我希望在粘贴操作后只有文本版本(无 html)。
目前我在我的组件上使用 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
})
第二部分,如果你想在原处添加cursor
粘贴
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))
}
推荐阅读
- react-native - 在下面的代码中 createappcontainer 没有渲染任何页面。只得到没有错误的白屏
- ios - 如何向我的 LocalizedStringKey 添加一些自定义文本?
- flutter - 如何从 MaterialPageRoute 中的构建器对象中获取 Widget 类名称
- qt - 如何使用 qml 中的加载器从另一个文件加载组件
- c# - 如何修复以下 LinQ 笛卡尔程序并使其正常工作?
- angular - Angular 库继承父应用程序模块
- azure-active-directory - 使用自动化脚本将来宾用户添加到 Azure AD?
- java - 在 pom.xml 中覆盖用于上传的存储库
- go - 服务器未响应 go echo 框架中的 API 调用
- excel - 如何删除小数点前的前导零?Excel 已格式化,但我的用户表单中的组合框正在添加它们