How to copy content to clipboard in JavaScript

亚连
Release: 2018-06-04 10:48:55
Original
2049 people have browsed it

There is a small requirement in a recent event page. Users can click or long-press to copy the content to the clipboard and record the implementation process and pitfalls encountered. Friends who need it can refer to it

Common methods

After checking the almighty Google, the common methods are mainly the following two:

Third-party library: clipboard.js
Native method: document. execCommand()

Let’s see how these two methods are used.

clipboard.js

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

Quote

Direct quote:

Copy after login

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

Use

Copy from the input box
Now there is an tag on the page, we need to copy it Content, we can do this:

 
Copy after login

import Clipboard from 'clipboard'; const btnCopy = new Clipboard('btn');
Copy after login

Notice that in

Copy after login

import Clipboard from 'clipboard'; const btnCopy = new Clipboard('btn'); this.copyValue = 'hello world';
Copy after login

Event

Sometimes we need to copy To do something, you need the support of callback function.

Add the following code to the processing function:

// 复制成功后执行的回调函数 clipboard.on('success', function(e) { console.info('Action:', e.action); // 动作名称,比如:Action: copy console.info('Text:', e.text); // 内容,比如:Text:hello word console.info('Trigger:', e.trigger); // 触发元素:比如: e.clearSelection(); // 清除选中内容 }); // 复制失败后执行的回调函数 clipboard.on('error', function(e) { console.error('Action:', e.action); console.error('Trigger:', e.trigger); });
Copy after login

##Summary

The document also mentions Yes, if you use

clipboard in a single page, in order to make life cycle management more elegant, remember tobtn.destroy() destroy it after use.

clipboard is very simple to use. However, is it not elegant enough to use additional third-party libraries just for a copy function? What should we do at this time? Then use native methods to achieve it.

document.execCommand() method

Let’s first look at how this method is defined on

MDN :

which allows one to run commands to manipulate the contents of the editable region.


means that you can allow one to run commands to manipulate the contents of the editable region. Note that it is an editable region.

Definition

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

The method returns a Boolean value indicating whether the operation was successful.

  • aCommandName: Indicates the command name, such as: copy, cut, etc. (see commands for more commands);

  • aShowDefaultUI: Whether to display the user interface , usually false;

  • aValueArgument: Some commands require additional parameters, which are generally not used;

compatible Sex

The compatibility of this method was not very good before, but fortunately it is now basically compatible with all mainstream browsers and can also be used on mobile terminals.

Copy from the input box using

##Now there is an tag on the page that we want to copy For the content, we can do this:


 
Copy after login

js code

const btn = document.querySelector('#btn'); btn.addEventListener('click', () => { const input = document.querySelector('#demoInput'); input.select(); if (document.execCommand('copy')) { document.execCommand('copy'); console.log('复制成功'); } })
Copy after login

Copy elsewhere

Sometimes there is no

tag on the page, we may need to copy from a

content, or copy the variable directly. Remember in the definition of the

execCommand()

method that it can only operate on editable areas, which means that except for inputs like and At this time we need to save the country.

js code

const btn = document.querySelector('#btn'); btn.addEventListener('click',() => { const input = document.createElement('input'); document.body.appendChild(input); input.setAttribute('value', '听说你想复制我'); input.select(); if (document.execCommand('copy')) { document.execCommand('copy'); console.log('复制成功'); } document.body.removeChild(input); })
Copy after login

It can be regarded as a success in saving the country through curves. When using this method, I encountered several pitfalls.

Pits encountered

When debugging under Chrome, this method runs perfectly. Then when it came to debugging the mobile terminal, the pit came out.

Yes, that’s right, it’s you, ios. . .

1. When you click copy, a white screen jitter will appear at the bottom of the screen. If you look carefully, you pull up the keyboard and put it away instantly.

Once you know what causes the jitter It's easier to solve. Since the keyboard is pulled up, the focus is on the input field. Then just make the input field unavailable for input. Add input.setAttribute('readonly', 'readonly'); to the code to make this read-only. Yes, it won't pull up the keyboard.

2. Unable to copy

这个问题是由于 input.select() 在ios下并没有选中全部内容,我们需要使用另一个方法来选中内容,这个方法就是 input.setSelectionRange(0, input.value.length);。

完整代码如下:

const btn = document.querySelector('#btn'); btn.addEventListener('click',() => { const input = document.createElement('input'); input.setAttribute('readonly', 'readonly'); input.setAttribute('value', 'hello world'); document.body.appendChild(input); input.setSelectionRange(0, 9999); if (document.execCommand('copy')) { document.execCommand('copy'); console.log('复制成功'); } document.body.removeChild(input); })
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

详细讲解使用Node.js写一个简单的命令行工具(详细教程)

在Node.js中使用cheerio制作简单的网页爬虫(详细教程)

在vue中如何实现父组件向子组件传递多个数据

The above is the detailed content of How to copy content to clipboard in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!