angularjs-兼容各种浏览器的复制到剪切板功能的代码

来源:互联网 发布:16年双十一淘宝交易额 编辑:程序博客网 时间:2024/05/22 12:07

实现原理就是:动态生成隐藏文本域,把要复制的内容放到该文本域,然后依次执行DOM里的选中,复制功能就可以(有些代码是非相关的可以忽略)。注意,不要在非直接点击触发的函数里用document.execCommand('copy')的方法,因为浏览器的安全机制会禁止使用。另外可以加判断ta是否已经生成过,如果生成过,直接用就可以(

  if(ta){return ta;}

方法代码:

copyJson(claimId) {  var self = this;    var copyClaimJsonUrl = this.urlUtils.getBackendApiUrl("claimDetail/copyClaimJson");    var model = "";    $.ajax({      type: "get",      dataType: "json",      data: {"claimId":  claimId},      async:false,      url: copyClaimJsonUrl,      success: function (data) {        if(data){          self.claimJson = JSON.stringify(data);        }      }    });  var ta =this.createTempTextArea();//创建文本域  document.body.appendChild(ta);  //后缀到DOM  ta.value = this.claimJson; //赋值  ta.select();                 //选中  var success =document.execCommand('copy');//复制  layer.msg("复制成功!");}
动态生成隐藏文本域的代码:
  
createTempTextArea = function () {  var isRTL = document.documentElement.getAttribute('dir') === 'rtl';
  var ta;  ta = document.createElement('textarea');  // Prevent zooming on iOS  ta.style.fontSize = '12pt';  // Reset box model  ta.style.border = '0';  ta.style.padding = '0';  ta.style.margin = '0';  // Move element out of screen horizontally  ta.style.position = 'absolute';  ta.style[isRTL ? 'right' : 'left'] = '-9999px';  // Move element to the same position vertically  var /** @type {?} */ yPosition = window.pageYOffset || document.documentElement.scrollTop;  ta.style.top = yPosition + 'px';  ta.setAttribute('readonly', '');  return ta;};

阅读全文
0 0
原创粉丝点击