JavaScript实现复制内容到粘贴板代码
最近做了一个前端项目,其中有需求:通过button直接把input或者textarea里的值复制到粘贴板里。下面小编把我实现思路及代码分享给大家,大家可以直接引入项目中。
具体代码如下所示:
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;
}
我们可以这样直接调用这个方法:
copyToClipboard(document.getElementById("name"));
这样id为name的值进入了粘贴板了。
关于JavaScript实现复制内容到粘贴板代码小编就给大家介绍到这里,希望对大家有所帮助!