Copy the specified text to the clipboard with one click
train of thought
- Use to
input
select the text to be copied - To perform a copy operation, the main use
document.execCommand('copy')
- delete
input
implementation details
- Create an input element to put the text content that needs to be copied
- Set its style so that it does not appear in the viewport so as not to affect the current page
- Need to judge the type of device, because some
API
Apple devices do not support - Deletes the created
input
element
full code
function handle_copy(textString) {
const input = document.createElement('input')
document.body.append(input)
input.style.position = 'absolute'
input.readOnly = 'readOnly'
input.style.left = '-1000px'
input.style.zIndex = '-100'
input.value = textString
const system = navigator.userAgent// 获取系统信息
// 苹果
if (system.match(/(iPhone|iPod|iPad);?/i)) {
window.getSelection().removeAllRanges() // 将页面所有的文本区域都从选区中移除
const copyDOM = input // 要复制文字的节点
const range = document.createRange()
// 选中需要复制的节点
range.selectNode(copyDOM)
// 执行选中元素
window.getSelection().addRange(range)
// 执行 copy 操作
const successful = document.execCommand('copy')
try {
var msg = successful ? '成功' : '失败'
this.$message('复制' + msg)
} catch (err) {
console.log(err)
}
// 移除选中的元素
window.getSelection().removeAllRanges()
return successful
}
// 安卓
// if (system.indexOf('Android') > -1) {
if (document.execCommand('copy')) {
input.select() // IOS不支持 鸿蒙暂不清楚
const status = document.execCommand('copy')
input.blur()
return status
}
// }
input.parentNode.removeChild(input)
}
The above content is only a summary of personal study and work. If there are any mistakes or better suggestions, please point them out.