大概思路就是在看不见的地方创建一个textarea,然后选中这个元素,然后通过document执行copy命令,再移除创建的这个元素
/**
*
* @desc 写入剪切板
* @param {String} str
*/
export function clipboard(str) {
const el = document.createElement('textarea')
el.value = str
el.setAttribute('readonly', '')
el.style.position = 'absolute'
el.style.left = '-9999px'
document.body.appendChild(el)
const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false
el.select()
document.execCommand('copy')
document.body.removeChild(el)
if (selected) {
document.getSelection().removeAllRanges()
document.getSelection().addRange(selected)
}
}