Home  >  Article  >  Web Front-end  >  JavaScript copy content to clipboard implementation code

JavaScript copy content to clipboard implementation code

小云云
小云云Original
2018-02-28 13:14:091371browse
<p>There is a small requirement in a recent activity page. Users can click or long-press to copy the content to the clipboard and record the implementation process and pitfalls encountered.

Common methods

<p>I checked the omnipotent Google, and now the common methods are mainly the following two:

  • <p>Third-party libraries: clipboard.js

  • <p>Native method: document.execCommand()

<p>Let’s see how these two methods are used.

clipboard.js

<p>This is the official website of clipboard: https://clipboardjs.com/, it seems so simple.

Quote

<p>Direct quote: <script src="dist/clipboard.min.js"></script>

<p>Package : npm install clipboard --save, then import Clipboard from 'clipboard';

Use

to copy

## from the input box #Now there is an <p><input> tag on the page, we need to copy the content inside it, we can do this:

<input id="demoInput" value="hello world">
<button class="btn" data-clipboard-target="#demoInput">点我复制</button>
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
Notice that in <p>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn