直接将此代码放入js文件中,导出引用就好啦~
function textFormat (e) {
e.preventDefault()
var text
var clp = (e.originalEvent || e).clipboardData
if (clp === undefined || clp === null) {
text = window.clipboardData.getData('text') || ''
if (text !== '') {
if (window.getSelection) {
var newNode = document.createElement('span')
newNode.innerHTML = text
window.getSelection().getRangeAt(0).insertNode(newNode)
} else {
document.selection.createRange().pasteHTML(text)
}
}
} else {
text = clp.getData('text/plain') || ''
if (text !== '') {
document.execCommand('insertText', false, text)
}
}
}
export { textFormat }
引用处~
- 若需要给每一个文本都添加'paste'的监听事件,就要用到循环,单个直接获取当前节点就可以了
- !el.paste 这个是解决重复添加'paste'监听事件,导致内容重复,如果没有动态添加文本功能,可以不要这个判断
- 代码是vue的写法,$nextTick是为了获取到所有节点的内容
import { textFormat } from '@/components/common.js'
this.$nextTick(() => {
const textArr = document.querySelectorAll('.wn-text')
textArr.forEach(el => {
if (!el.paste) {
el.addEventListener('paste', e => {
el.paste = true
textFormat(e)
})
}
})
});