四时宝库

程序员的知识宝库

前端必修课之原生 JS 实现复制文本



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

代码块

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('今日头条!')

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接