js 点击复制(pc,安卓,ios,微信)

扩展js:clipboard.js

地址:https://clipboardjs.com/


Why

Copying text to the clipboard shouldn't be hard. It shouldn't require dozens of steps to configure or hundreds of KBs to load. But most of all, it shouldn't depend on Flash or any bloated framework.

That's why clipboard.js exists.

Install

You can get it on npm.

npm install clipboard --save

Or bower, too.

bower install clipboard --save

If you're not into package management, just download a ZIP file.

Setup

First, include the script located on the dist folder or load it from a third-party CDN provider.

<script src="dist/clipboard.min.js">script>

Now, you need to instantiate it by passing a DOM selector, HTML element, or list of HTML elements.

new Clipboard('.btn');

Internally, we need to fetch all elements that matches with your selector and attach event listeners for each one. But guess what? If you have hundreds of matches, this operation can consume a lot of memory.

For this reason we use event delegation which replaces multiple event listeners with just a single listener. After all, #perfmatters.

Usage

We're living a declarative renaissance, that's why we decided to take advantage of HTML5 data attributes for better usability.

Copy text from another element

A pretty common use case is to copy content from another element. You can do that by adding a data-clipboard-targetattribute in your trigger element.

The value you include on this attribute needs to match another's element selector.


<input id="foo" value="https://github.com/zenorocha/clipboard.js.git">


<button class="btn" data-clipboard-target="#foo">
    <img src="assets/clippy.svg" alt="Copy to clipboard">
button>

Cut text from another element

Additionally, you can define a data-clipboard-action attribute to specify if you want to either copy or cut content.

If you omit this attribute, copy will be used by default.

Cut to clipboard

<textarea id="bar">Mussum ipsum cacilds...textarea>


<button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
    Cut to clipboard
button>

As you may expect, the cut action only works on  or