欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
  搜罗到两种兼容性还不错的方式。
 
  1、第一种,通过clipboard.js插件实现(推荐)
 
  此插件封装了很多种使用方式很方便,具体demo,可以去GitHub上看,clipboard传送门
 
  2、第二种,纯js实现:
 
  <!DOCTYPEhtml>
 
  <htmllang="en">
 
  <head>
 
  <metacharset="UTF-8">
 
  <title>CopyDemo</title>
 
  </head>
 
  <body>
 
  <divid=NewsToolBox></div>
 
  <divid="text-content">
 
  <p>测试p1</p>
 
  <p>测试p2</p>
 
  </div>
 
  <buttonid="copy-text-btn">复制</button>
 
  </body>
 
  </html>
 
  <scripttype="text/javascript">
 
  //复制全文
 
  document.getElementById("copy-text-btn").onclick=function(){
 
  varssrsss=document.getElementById("text-content").innerText.replace(/\+/g,"");//获取文本并去掉空格
 
  varflag=copyText(ssrsss);//传递文本
 
  alert(flag?'复制成功':'复制失败')
 
  };
 
  functioncopyText(text){
 
  vartextarea=document.createElement("textarea");//创建input对象
 
  varcurrentFocus=document.activeElement;//当前获得焦点的元素
 
  vartoolBoxwrap=document.getElementById('NewsToolBox');//将文本框插入到NewsToolBox这个之后
 
  toolBoxwrap.appendChild(textarea);//添加元素
 
  textarea.value=text;
 
  textarea.focus();
 
  if(textarea.setSelectionRange){
 
  textarea.setSelectionRange(0,textarea.value.length);//获取光标起始位置到结束位置
 
  }else{
 
  textarea.select();
 
  }
 
  try{
 
  varflag=document.execCommand("copy");//执行复制
 
  }catch(eo){
 
  varflag=false;
 
  }
 
  toolBoxwrap.removeChild(textarea);//删除元素
 
  currentFocus.focus();
 
  returnflag;
 
  }
 
  </script>
 
  上面两种方式兼容性都不错,亲测可用。

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h56666.shtml