温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-10-25 08:20:43 来源:脚本之家 阅读:475 作者:锅子博客 栏目:web开发

前言

最近在做一个按钮,实现的效果是当点击后复制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}" />
 </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的样式用进行隐藏,因为不知道为什么用type="hiden"或者display="none"去隐藏都只会获取源代码而不是动态的url遍历出来的值。

总结

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI