使用于前端开发过程中需要复制文本内容场景。兼容性比较好!
- copy.js文件
export default input => { // input为传入参数
const el = document.createElement('textarea')
el.value = input
el.setAttribute('readonly', '')
el.style.contain = 'strict'
el.style.position = 'absolute'
el.style.left = '-9999px'
el.style.fontSize = '12pt'
const selection = document.getSelection()
let originalRange = false
if (selection.rangeCount > 0) {
originalRange = selection.getRangeAt(0)
}
document.body.appendChild(el)
el.select()
el.selectionStart = 0
el.selectionEnd = input.length
let success = false
try {
success = document.execCommand('copy')
/* eslint-disable */
} catch (err) {}
document.body.removeChild(el)
if (originalRange) {
selection.removeAllRanges()
selection.addRange(originalRange)
}
return success
}
- 使用
import copy from 'copy.js'; //引入
copy('需要复制的文本') //直接使用