JavaScript: click the button to copy the text of a specified area

Source: Internet
Author: User
JavaScript: click the button to copy the text in the specified area html5 webAPI interface can easily use a few lines of code to copy the text in the area by clicking the button, without the need to rely on flash.

The Code is as follows:

/* Create a range object */const range = document. createRange (); range. selectNode (element); // set the Node object included in the range/* The selection object of the window, indicating the selected text */const selection = window. getSelection (); if (selection. rangeCount> 0) selection. removeAllRanges (); // clear the selection of the included selected objects. addRange (range); // upload the rangeobject of the replica to document.exe cCommand ('copy') in the selectionobject; // run the copy command to copy the selected text.


Test:

The browser version is the version I used for testing.

Edge browser, Chrome (v54.0.2840.99 m), and Firefox (v49.0.1) are available.

IE9, IE10, and IE11 will pop up with a prompt asking whether to paste the text to the clipboard.

IE7 and IE8 do not support this function.

The Safari browser of IOS10 is available.

According to feedback, Safari browsers under IOS9 should not support this function.

Demo:

 TitleOne-day Park Tour2016.8.15 Tuesday

Today, I went to the People's Park with Xiaohong and played slide, snowball fights, and boating. It was a pleasant day.

Copy an articleScript function copyArticle (event) {const range = document. createRange (); range. selectNode (document. getElementById ('Article'); const selection = window. getSelection (); if (selection. rangeCount> 0) selection.removeallranges(registry.selection.addrange(range=document.exe cCommand ('copy');} document. getElementById ('copy '). addEventListener ('click', copyArticle, false); script
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.