选中: Selection API/Range API
复制: execCommand
<div id="copy">测试复制</div>
document.getElementById('copy').addEventListener('click',()=>{
const value = '需要复制的内容'
clip(value,()=>{
console.log('成功')
})
})
function clip (value, success) {
const input = document.createElement('input');
input.setAttribute('readonly', 'readonly');
input.setAttribute('value', value);
document.body.appendChild(input);
input.select();
input.setSelectionRange(0, 9999); //控制光标的位置
if (document.execCommand) {
document.execCommand('copy');
// add tips
if (success) {
success();
}
}
document.body.removeChild(input);
}