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

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

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

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

<tr> <td> <a>复制文件链接</a> <input 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的样式用style="margin-left: -9999px"进行隐藏,因为不知道为什么用type="hiden"或者display="none"去隐藏都只会获取源代码而不是动态的url遍历出来的值。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwgpgp.html