JavaScript implements _javascript tips for copying content to paste board code

Source: Internet
Author: User
Tags tagname

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.