Home > Article > Web Front-end > How to copy content to clipboard in JavaScript
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 'clipboard'; const btnCopy = new Clipboard('btn');
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 'clipboard'; const btnCopy = new Clipboard('btn'); 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 useclipboard in a single page, in order to make life cycle management more elegant, remember to
btn.destroy() destroy it after use.
document.execCommand() method
Let’s first look at how this method is defined onMDN:
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('#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
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
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('#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 success in saving the country through curves. When using this method, I encountered several pitfalls.
Pits encounteredWhen 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);。 完整代码如下: 上面是我整理给大家的,希望今后会对大家有帮助。 相关文章: 详细讲解使用Node.js写一个简单的命令行工具(详细教程) 在Node.js中使用cheerio制作简单的网页爬虫(详细教程)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);
})
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!