当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS复制对应id的内容到粘贴板(Ctrl+C效果)

JS复制对应id的内容到粘贴板(Ctrl+C效果)

2019年03月28日  | 移动技术网IT编程  | 我要评论

前言

最近在做一个按钮,实现的效果是当点击后复制url到黏贴板,但不是当前页面url,而是对应一个元素的url,且一个页面会有多个url。一开始找到一个方法,但是竟然只兼容ie浏览器,神奇了,竟然有只兼容ie的东西。后来发现一个zeroclipboard.js这个插件,但是怎么也搞不出那个效果,有点麻烦。

最后翻到了一个js封装好的方法,有效!

想要实现的一个效果是,下面html代码:

<tr>
 <td>
 <a id="copy_{$key}" onclick="geturl('{$key}')">复制文件链接</a>
 <input id="file_{$key}" value="{$file.file_url}" style="margin-left: -9999px"/>
 </td>
</tr> 

点击复制文件链接这个按钮,复制input框里的value值,是传进去的一个url;首先点击a标签会触发geturl这个函数;传进去id用于找到对应的input然后取值(因为遍历了多个td,有许多个input框一一对应去取)。

下面js代码:

<pre><script type="application/javascript">
 
 function geturl(id) {
  if (copytoclipboard(document.getelementbyid("file_"+id))){
   alert("成功复制到黏贴板!");
  }else{
   alert("复制到黏贴板失败!");
  }
 }
 
 function copytoclipboard(elem) {
  // create hidden text element, if it doesn't already exist
  var targetid = "_hiddencopytext_";
  var isinput = elem.tagname === "input" || elem.tagname === "textarea";
  var origselectionstart, origselectionend;
  if (isinput) {
   // can just use the original source element for the selection and copy
   target = elem;
   origselectionstart = elem.selectionstart;
   origselectionend = elem.selectionend;
  } else {
   // must use a temporary form element for the selection and copy
   target = document.getelementbyid(targetid);
   if (!target) {
    var target = document.createelement("textarea");
    target.style.position = "absolute";
    target.style.left = "-9999px";
    target.style.top = "0";
    target.id = targetid;
    document.body.appendchild(target);
   }
   target.textcontent = elem.textcontent;
  }
  // select the content
  var currentfocus = document.activeelement;
  target.focus();
  target.setselectionrange(0, target.value.length);
 
  // copy the selection
  var succeed;
  try {
   succeed = document.execcommand("copy");
  } catch(e) {
   succeed = false;
  }
  // restore original focus
  if (currentfocus && typeof currentfocus.focus === "function") {
   currentfocus.focus();
  }
 
  if (isinput) {
   // restore prior selection
   elem.setselectionrange(origselectionstart, origselectionend);
  } else {
   // clear temporary content
   target.textcontent = "";
  }
  return succeed;
 }
</script></pre>

geturl中调用了封装好的copytoclipboard方法实现了功能。有一点的是html中input的样式用style="margin-left: -9999px"进行隐藏,因为不知道为什么用type="hiden"或者display="none"去隐藏都只会获取源代码而不是动态的url遍历出来的值。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网