Recently done a front-end project, which has the demand: through the button directly to the input or textarea in the value of the copy to the Clipboard. The following small series to my realization of ideas and code to share to you, you can directly introduce the project.
The specific code looks like this:
function CopyToClipboard (elem) {//create hidden text element, if it doesn ' t already exist var Targetid = ' _hiddencopyte
Xt_ "; 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 = "-9999
PX ";
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 = = "Funct Ion ") {Currentfocus.focus ();} if (isinput) {//restore prior selection elem.setselectionrange (Origselectionstart, Origs
Electionend);
else {//clear temporary content target.textcontent = "";}
return succeed; }
We can call this method directly:
CopyToClipboard (document.getElementById ("name"));
The value with ID name enters the pasteboard.
About the JavaScript implementation of the copy content to the Paste Board code small series to introduce you here, I hope to help!