AlexZ33 / lessions

自己练习的各种demo和课程
12 stars 2 forks source link

JavaScript复制内容到剪贴板 #121

Open AlexZ33 opened 3 years ago

AlexZ33 commented 3 years ago
HTML
<input id="demoInput" value="hello world">
<button id="btn">点我复制</button>
JS(安卓)
const btn = document.querySelector('#btn'); 
btn.addEventListener('click', () => {         
    const input = document.querySelector('#demoInput');         
    input.select();         
    if (document.execCommand('copy')) { 
    document.execCommand('copy');                 
    console.log('复制成功');         
    } 
})

IOS
const btn = document.querySelector('#btn'); 
btn.addEventListener('click',() => {         
    const input = document.createElement('input');
    input.setAttribute('readonly', 'readonly');    
    input.setAttribute('value', 'hello world');
    document.body.appendChild(input);         
    input.setSelectionRange(0, 9999);         
    if (document.execCommand('copy')) {
        document.execCommand('copy');                 
        console.log('复制成功');         
    }    
    document.body.removeChild(input); 
})