是否可以使用 Javascript 复制到剪贴板?

我正在开发一个 sharepoint webpart,它有一个按钮,可以从同一页面上的不同文本框中拉取元素,并将它们整理成一个字符串,然后复制到用户的剪贴板,以便他们可以快速地将某个问题的通信放在一起。到目前为止,我有以下代码,但实际上并没有复制任何内容。我已经通过 JSHint 运行了它,但没有发现任何问题,但是我在函数底部找到了代码,用于从关于如何与剪贴板 API 交互的教程中复制文本以从文本框中复制文本,因此为什么我将所有内容添加到 smsToSend 文本区域。给人们的注意是,如果有一个全新的问题并且以前没有发出过,那么事件更新总是“我们正在调查这个问题”


function generateSMS(){

 var issueTitle = document.getElementById("incidentTitle");

 var advisorImpact = document.getElementById("advisorImpact");

 var incidentUpdate = document.getElementById("incidentUpdate");

 var incidentStatus = document.getElementById("incidentState");

 var startTime = document.getElementById("startTime");

 var endTime = document.getElementById("endTime");

 var smsToSend = document.createElement('textarea');

 var incidentPriority = document.getElementById("incidentPriority");

 var incidentBrand = "TechTeams";

 var systemImpacted = document.getElementById("systemImpacted");

 var incidentReference = document.getElementById("incidentReference");


 if (incidentStatus != "Closed"){

     if (incidentUpdate == "We are investigating this issue"){

         smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT ISSUE: " + systemImpacted + ": " + issueTitle + ". " + advisorImpact + ": " + incidentReference;

     }

     else {

         smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT UPDATE: " + systemImpacted + ": " + incidentUpdate + ": " + incidentReference;

     }

 }

 else{

     smsToSend = "P" + incidentPriority + " " + incidentBrand + "IT RESOLVED: " + systemImpacted + ": " + incidentUpdate + ": Start: " + startTime + " End: " + endTime + " Reference: " + incidentReference;

 }


 smsToSend.setAttribute('readonly','');

  smsToSend.style = {position: 'absolute', left: '-9999px'};

  document.body.appendChild(smsToSend);

  smsToSend.select();

  document.execCommand('copy');

  document.body.removeChild(smsToSend);

}


神不在的星期二
浏览 138回答 1
1回答

婷婷同学_

您可以使用 js 轻松复制到剪贴板,如下所示:function CopyToClipboard(text) {&nbsp; &nbsp; /* Get the text field */&nbsp; &nbsp; var copyText = document.getElementById("elementId").textContent; //here you get the text&nbsp; &nbsp; var dummy = $('<textarea>').val(copyText).appendTo('body').select();&nbsp; &nbsp; document.execCommand('copy');//here the text gets copyed&nbsp; &nbsp; alert("Text copyed to clipboard!");&nbsp; &nbsp; $(dummy).remove();// here you remove the dummy that has been created previously}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript