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

JavaScript copy content to clipboard implementation code

小云云
小云云Original
2018-02-28 13:14:091562browse

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

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

  • Third-party libraries: 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

to copy

## from the input box #Now there is an

<input> tag on the page, we need to copy the content inside it, we can do this:

<input>
<button>点我复制</button>
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
Notice that in

Copy directly

Sometimes, we don’t want to copy the content from

<input>, but just get the value directly from the variable. If we can do this in Vue:

<button>点我复制</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 support of callback function. <p></p>Add the following code to the processing function: <p></p>
// 复制成功后执行的回调函数
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>点我复制</button>
    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 is more elegant. Remember btn.destroy() to destroy it after use.

clipboard Isn’t it very simple to use? However, is it not elegant enough to use additional third-party libraries just for a copy function? What should I 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 running commands to manipulate the contents of the editable region. Note that it is

editable region.

Definition

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
The method returns a

Boolean value, indicating whether the operation was successful.

  • aCommandName: Represents 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;

Compatibility

The compatibility of this method before was actually not That's great, but fortunately it is now basically compatible with all major browsers and can also be used on mobile devices. <p></p>

JavaScript copy content to clipboard implementation code

Copy from the input box using

Now there is an

<input> on the page tag, we want to copy the content, we can do this:

<input>
<button>点我复制</button>
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

<input>## on the page # tag, we may need to copy the content from a <p></p>, or copy the variable directly. Remember in the definition of the

execCommand()

method that it can only operate editable areas, which means that except and <textarea></textarea>. At this time we need to save the country.

<button>点我复制</button>
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.

Pits Encountered

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

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

<p></p>
    When you click copy, a white screen jitter will appear at the bottom of the screen. If you look carefully, you can pull up the keyboard and put it away instantly.
  1. It would be better if you know what causes the jitter. solved. Since the keyboard is pulled up, the focus is on the input field, so just make the input field unavailable for input. Add

    input.setAttribute('readonly', 'readonly');

    to the code to make this<input> is read-only, so the keyboard will not be pulled up.

  2. Cannot copy
  3. 这个问题是由于 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);
})

相关推荐:

JS复制内容到剪切板的实例代码(兼容IE与火狐)_javascript技巧

jQuery插件Zclip实现完美兼容个浏览器点击复制内容到剪贴板_jquery

JavaScript实现复制内容到粘贴板代码_javascript技巧

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