Home  >  Article  >  Web Front-end  >  JS to copy content to clipboard

JS to copy content to clipboard

php中世界最好的语言
php中世界最好的语言Original
2018-05-16 16:49:342775browse

This time I will bring you JS to copy content to the clipboard and JS to copy content to the clipboard. What are the precautions?. Here is a practical case. Let’s take a look.

Common methods

I checked the omnipotent Google, and now 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

Quote

Direct quote:

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

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

Use

to copy from the input box
now There is an d5fd7aea971a85678ba271703566ebfd tag on the page, and we need to copy the content inside it. We can do this:

101d2f0351ffa1654f54f73ea413e6f4
34d7634e8dc05677951405c4b6cbcee6点我复制65281c5ac262bf6d81768915a4a77ac0
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');

Notice that a ## is added to the bb9345e55eb71822850ff156dfde57c8 tag #data-clipboard-target Attribute, its value is the id of the d5fd7aea971a85678ba271703566ebfd that needs to be copied. As the name suggests, it copies the content from the entire 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 'clipboard';
const btnCopy = new Clipboard('btn');
this.copyValue = 'hello world';

Event

Sometimes we need to do something after copying, then we need the

callback function support.

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); // 触发元素:比如:ed77c0f0d1a4e9c4032e2f7c73cffb1b点我复制65281c5ac262bf6d81768915a4a77ac0
 e.clearSelection(); // 清除选中内容
});
// 复制失败后执行的回调函数
clipboard.on('error', function(e) {
 console.error('Action:', e.action);
 console.error('Trigger:', e.trigger);
});

Summary

The document also mentions that if

clipboard is used in a single page , in order to make life cycle management more elegant, remember btn.destroy() to 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.

This means that commands can be run to manipulate the contents of the editable area. Note that it is an editable area.

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 actually 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:

101d2f0351ffa1654f54f73ea413e6f4
ddbd97e11a826e220b707861b3166e92点我复制65281c5ac262bf6d81768915a4a77ac0

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 elsewhere

Sometimes there is no

on the page d5fd7aea971a85678ba271703566ebfd

tag, we may need to copy the content from a e388a4556c0f65e1904146cc1a846bee, 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.

<button id="btn">点我复制</button>

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);
})

It can be regarded as a successful curve to save the country. Several pitfalls were encountered when using this method.

遇到的坑

在Chrome下调试的时候,这个方法时完美运行的。然后到了移动端调试的时候,坑就出来了。

对,没错,就是你,ios。。。

1、点击复制时屏幕下方会出现白屏抖动,仔细看是拉起键盘又瞬间收起

知道了抖动是由于什么产生的就比较好解决了。既然是拉起键盘,那就是聚焦到了输入域,那只要让输入域不可输入就好了,在代码中添加 input.setAttribute('readonly', 'readonly'); 使这个 d5fd7aea971a85678ba271703566ebfd 是只读的,就不会拉起键盘了。

2、无法复制

这个问题是由于 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);
})

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

javascript模块加载器是怎么运行的

怎样实现微信web端后退强制刷新

The above is the detailed content of JS to copy content to clipboard. 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