移动端和pc端的复制到剪贴板功能

一.Document.execCommand()

1.移动端复制

html结构

礼包码: 复制

js代码

if(!isPC){
      $('.helper-box').on('click','.gift-code-copy',function(){    
        var inputText=$(this).prev('.gift-code-code').prev('.gift-code-info');
        var copyText=$(this).prev('.gift-code-code');
        console.log(inputText.val(),copyText.text());
        if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)){
            window.getSelection().removeAllRanges();
            var range = document.createRange();
            range.selectNode(copyText[0]);
            util.console.log('range:', range);
            window.getSelection().addRange(range);
    
            var result = document.execCommand('copy');
            if(result){
                popup.toast('复制成功');
            }else{
                popup.toast('复制失败');
            }
            window.getSelection().removeAllRanges();
        }else{
            inputText.select();
            var result = document.execCommand('copy', false);
            if(result){
                popup.toast('复制成功');
            }else{
                popup.toast('复制失败');
            }
        }

    })
  }

2.pc端的复制

注:IE仅支持IE9+

if(isPC){
        $('.helper-box').on('click','.gift-code-copy',function(){    
            var inputText=$(this).prev('.gift-code-code').prev('.gift-code-info');
            var copyText=$(this).prev('.gift-code-code');
            console.log(inputText.val(),copyText.text());          
            inputText.select();
            document.execCommand("Copy","false",null)
  
        })
    }  
    

document.execCommand()文档:
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand
document.execCommand()参考文章:
https://www.cnblogs.com/xhyu/p/5370111.html

二.jquery.zclip+flash

加载jQuery和zClip,地址请根据各自的存放地址做相应修改。


js实现点击复制的代码

html

复制链接

注意:
1.zclip由于在target可见之前不能注册的问题,需要在显示后调用此方法进行注册;
2.不能跨域使用;
3.本地测试无法使用,需上传到服务器;
4.确保有Flash支持;
5.如果复制的内容来自输入框input,textarea等,copy对象使用:

copy:function(){
   return $(xxx).val();
}

6.如果复制的内容来自页面元素div、p之类的,copy对象使用:

copy:$(xxx).text();

7.配置说明

path:swf的路径(复制主要是用flash解决不同浏览器的复制)
copy:待复制的内容, 可以是静态内容, 也可以 return 动态内容
beforeCopy:复制之前要做的function;
afterCopy:复制之后要做的function;

8.提供了三方法

show:$(selected).zclip('show'); //复制功能有效
hide:$(selected).zclip('hide'); //复制功能无效
remove:$(selected).zclip('remove'); //完全移除复制功能

三.clipboard.js

没有Flash,没有框架
1.下载引入clipboard.js
2.实例化:new ClipboardJS( );
3.用法:可以复制、剪切、从属性复制文本;
复制:通过data-clipboard-target在触发器元素中添加属性来实现
可以定义data-clipboard-action属性以指定是要copy还是cut内容,如果省略此属性,copy则默认使用。
剪切:cut操作仅适用于