Home >Web Front-end >JS Tutorial >JavaScript copy content to clipboard implementation code
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.
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.
This is the official website of clipboard: https://clipboardjs.com/, it seems so simple.
Direct quote: <script src="dist/clipboard.min.js"></script>
Package : npm install clipboard --save
, then import Clipboard from 'clipboard';
<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 directlySometimes, 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';EventSometimes 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); });SummaryThe 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.
MDN:
editable region.
Definitionbool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)The method returns aBoolean 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;
<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 elsewhereSometimes 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
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
Yes, that’s right, it’s you, ios. . .
<p></p>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.
这个问题是由于 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!