[问题探讨]js一键复制功能

荒凉一梦 提交于 2020-01-23 01:12:18

需求: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}`)
})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!