Skip to content

JavaScript复制内容到剪贴板 #121

@AlexZ33

Description

@AlexZ33
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); 
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions