Home  >  Article  >  Web Front-end  >  How to copy content to clipboard in JavaScript

How to copy content to clipboard in JavaScript

亚连
亚连Original
2018-06-04 10:11:462158browse

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:

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

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

Use

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

<input id="demoInput" value="hello world">
<button class="btn" data-clipboard-target="#demoInput">点我复制</button>

import Clipboard from &#39;clipboard&#39;;
const btnCopy = new Clipboard(&#39;btn&#39;);

Notice that in bb9345e55eb71822850ff156dfde57c8 A data-clipboard-target attribute is added to the tag. Its value is the id of the d5fd7aea971a85678ba271703566ebfd that needs to be copied. As the name suggests, it is from Copy content throughout the tag.

Direct copy

Sometimes, we don’t want to copy the content from d5fd7aea971a85678ba271703566ebfd, but just get the value directly from the variable. If we can do this in Vue:

<button class="btn" :data-clipboard-text="copyValue">点我复制</button>

import Clipboard from &#39;clipboard&#39;;
const btnCopy = new Clipboard(&#39;btn&#39;);
this.copyValue = 'hello world';

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); // 触发元素:比如:<button class="btn" :data-clipboard-text="copyValue">点我复制</button>
 e.clearSelection(); // 清除选中内容
});

// 复制失败后执行的回调函数
clipboard.on('error', function(e) {
 console.error('Action:', e.action);
 console.error('Trigger:', e.trigger);
});

##Summary

The document also mentions Yes, if you use

clipboard in a single page, in order to make life cycle management more elegant, remember to btn.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 d5fd7aea971a85678ba271703566ebfd tag on the page that we want to copy For the content, we can do this:


<input id="demoInput" value="hello world">
<button id="btn">点我复制</button>

js code

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

Copy elsewhere

Sometimes there is no

d5fd7aea971a85678ba271703566ebfd

tag on the page, we may need to copy from a e388a4556c0f65e1904146cc1a846bee 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 d5fd7aea971a85678ba271703566ebfd and 4750256ae76b6b9d804861d8f69e79d3 This method cannot be used outside the domain. At this time we need to save the country.

0daa849bc639fff17b006ca8cf3a07caClick me to copy65281c5ac262bf6d81768915a4a77ac0

js code

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

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 d5fd7aea971a85678ba271703566ebfd 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(&#39;#btn&#39;);
btn.addEventListener(&#39;click&#39;,() => {
	const input = document.createElement(&#39;input&#39;);
 input.setAttribute(&#39;readonly&#39;, &#39;readonly&#39;);
 input.setAttribute(&#39;value&#39;, &#39;hello world&#39;);
 document.body.appendChild(input);
	input.setSelectionRange(0, 9999);
	if (document.execCommand(&#39;copy&#39;)) {
		document.execCommand(&#39;copy&#39;);
		console.log(&#39;复制成功&#39;);
	}
 document.body.removeChild(input);
})

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

相关文章:

详细讲解使用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!

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