JS复制对应id的内容到粘贴板(Ctrl+C效果)
前言
最近在做一个按钮,实现的效果是当点击后复制url到黏贴板,但不是当前页面url,而是对应一个元素的url,且一个页面会有多个url。一开始找到一个方法,但是竟然只兼容IE浏览器,神奇了,竟然有只兼容IE的东西。后来发现一个zeroclipboard.js这个插件,但是怎么也搞不出那个效果,有点麻烦。
最后翻到了一个js封装好的方法,有效!
想要实现的一个效果是,下面html代码:
<tr>
<td>
<aid="copy_{$key}"onclick="getUrl('{$key}')">复制文件链接</a>
<inputid="file_{$key}"value="{$file.file_url}"style="margin-left:-9999px"/>
</td>
</tr>
点击复制文件链接这个按钮,复制input框里的value值,是传进去的一个url;首先点击a标签会触发getUrl这个函数;传进去id用于找到对应的input然后取值(因为遍历了多个td,有许多个input框一一对应去取)。
下面js代码:
<pre><scripttype="application/javascript">
functiongetUrl(id){
if(copyToClipboard(document.getElementById("file_"+id))){
alert("成功复制到黏贴板!");
}else{
alert("复制到黏贴板失败!");
}
}
functioncopyToClipboard(elem){
//createhiddentextelement,ifitdoesn'talreadyexist
vartargetId="_hiddenCopyText_";
varisInput=elem.tagName==="INPUT"||elem.tagName==="TEXTAREA";
varorigSelectionStart,origSelectionEnd;
if(isInput){
//canjustusetheoriginalsourceelementfortheselectionandcopy
target=elem;
origSelectionStart=elem.selectionStart;
origSelectionEnd=elem.selectionEnd;
}else{
//mustuseatemporaryformelementfortheselectionandcopy
target=document.getElementById(targetId);
if(!target){
vartarget=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;
}
//selectthecontent
varcurrentFocus=document.activeElement;
target.focus();
target.setSelectionRange(0,target.value.length);
//copytheselection
varsucceed;
try{
succeed=document.execCommand("copy");
}catch(e){
succeed=false;
}
//restoreoriginalfocus
if(currentFocus&&typeofcurrentFocus.focus==="function"){
currentFocus.focus();
}
if(isInput){
//restorepriorselection
elem.setSelectionRange(origSelectionStart,origSelectionEnd);
}else{
//cleartemporarycontent
target.textContent="";
}
returnsucceed;
}
</script></pre>
getUrl中调用了封装好的copyToClipboard方法实现了功能。有一点的是html中input的样式用style="margin-left:-9999px"进行隐藏,因为不知道为什么用type="hiden"或者display="none"去隐藏都只会获取源代码而不是动态的url遍历出来的值。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。