MENU

原生JS实现复制文本

• May 29, 2020 • Read: 1827 • Web Program

公司最近一个需求 需要通过变量实现复制

效果

请双击我 哈哈哈哈

代码

window.copyText = item => {//挂载到全局
            var textArea = document.createElement('textArea');
            textArea.innerHTML = item;
            textArea.value = item;
            document.body.appendChild(textArea);
            textArea.select();
            try{
                if(document.execCommand("Copy")){
                    alert(`${item}  复制成功!`)
                }else{
                    alert('复制失败!请手动复制!') 
                }
            }
            catch(err){
                alert('复制错误!请手动复制!') 
            }
                document.body.removeChild(textArea);
}
使用
 window.copyText('你好')
Archives QR Code
QR Code for this page
Tipping QR Code