需求:js一键复制指定元素内容
实现:
1,commonFunc.js
function copyText(selector) {
return new Promise((resolve, reject) => {
// 获取需要copy的内容
const copyItem = document.querySelector(selector)
// 创建input
const input = document.createElement('input')
input.type = 'text'
input.style.position = 'fixed'
input.style.top = '100vh'
document.body.appendChild(input)
// 给你input赋值
input.value = copyItem.innerText
// 选中input文本
input.select()
// 执行复制命令
document.execCommand('copy')
// 移除dom
input.remove()
resolve('复制成功!')
})
}
const commonFunc = {
copyText
}
export default commonFunc
2,组件内使用
// 通用功能
import commonFunc from '@/utils/commonFunc'
// selector需要匹配指定 CSS 选择器,指向唯一元素,比如'#newsContent'
commonFunc.copyText(selector).then((res) => {
console.log('复制成功')
}).catch((err) => {
console.log(`复制失败,原因是commonFunc.copyText方法报错:${err.message}`)
})