// 内容
var text = ‘’
// 贴贴数据
var clp = (e.originalEvent || e).clipboardData
// 贴贴内容
if (clp && clp.getData) {
text = clp.getData(‘text/plain’) || ‘’
} else if (window.clipboardData && window.clipboardData.getData) {
text = window.clipboardData.getData(‘text’) || ‘’
}
// 内容不为空
if (text !== ‘’) {
// 数据是否满足指定格式
if (clp === undefined || clp === null) {
// 是否有光标位置
if (window.getSelection) {
// 有则插入指定位置
var newNode = document.createElement(‘span’)
newNode.innerHTML = text
window.getSelection().getRangeAt(0).insertNode(newNode)
} else {
// 没有则直接贴贴
document.selection.createRange().pasteHTML(text)
}
// 需要手动调用 oninput 输入事件
} else {
// 插入内容,会自动调用 oninput 输入事件
document.execCommand(‘insertText’, false, text)
}
}
}
// 方式二:不会保留文本原格式,需要手动调用 oninput 输入事件
function handlePaste2 (e) {
// 内容
var text = ‘’
// 贴贴事件
var clp = (e.originalEvent || e).clipboardData
// 贴贴内容
if (clp && clp.getData) {
text = clp.getData(‘text/plain’) || ‘’
} else if (window.clipboardData && window.clipboardData.getData) {
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)
}
// 需要手动调用 oninput 输入事件
}
}
// 方式三:方式一的升级版,保留原格式,但是会进行文本排版优化,去除多余的空格换行符
function handlePaste3 (e) {
// 内容
var text = ‘’
// 贴贴数据
var clp = (e.originalEvent || e).clipboardData
// 贴贴内容
if (clp && clp.getData) {
text = clp.getData(‘text/plain’) || ‘’
} else if (window.clipboardData && window.clipboardData.getData) {
text = window.clipboardData.getData(‘text’) || ‘’
}
// 内容不为空
if (text !== ‘’) { 《大厂前端面试题解析+Web核心总结学习笔记+企业项目实战源码+最新高清讲解视频》无偿开源 徽信搜索公众号【编程进阶路】
// 替换内容中间的全角空格为普通空格
text = text.replaceAll(/ +/, ’ ')
// 移除开头回车空格
text = text.replaceAll(/^\s+/, ‘’)
// 将内容中间换行空格替换成换行
text = text.replaceAll(/\n\s+/, ‘\n’)
// 替换内容中间多余的空格
text = text.replaceAll(/ +/, ’ ')
// 数据是否满足指定格式
if (clp === undefined || clp === null) {
// 是否有光标位置
if (window.getSelection) {
// 有则插入指定位置
var newNode = document.createElement(‘span’)
newNode.innerHTML = text
window.getSelection().getRangeAt(0).insertNode(newNode)
} else {
// 没有则直接贴贴
document.selection.createRange().pasteHTML(text)
}
// 需要手动调用 oninput 输入事件
} else {
// 插入内容,会自动调用 oninput 输入事件
document.execCommand(‘insertText’, false, text)
}