<p>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
<p>I checked the omnipotent Google, and now the common methods are mainly the following two:
<p>Third-party libraries: clipboard.js
<p>Native method: document.execCommand()
<p>Let’s see how these two methods are used.
clipboard.js
<p>This is the official website of clipboard: https://clipboardjs.com/, it seems so simple.
Quote
<p>Direct quote:
<script src="dist/clipboard.min.js"></script>
<p>Package :
npm install clipboard --save
, then
import Clipboard from 'clipboard';
Use
to copy ## from the input box #Now there is an <p><input>
tag on the page, we need to copy the content inside it, we can do this:
<input id="demoInput" value="hello world">
<button class="btn" data-clipboard-target="#demoInput">点我复制</button> Copy after login
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn'); Copy after login
Notice that in <p>
A
data-clipboard-target attribute is added to the tag. Its value is the
id of the
<input> that needs to be copied. As the name suggests, it is from the entire tag. Copy content in.
Copy directly Sometimes, we don’t want to copy the content from <p><input>, but just get the value directly from the variable. If we can do this in
Vue:
<button class="btn" :data-clipboard-text="copyValue">点我复制</button> Copy after login
import Clipboard from 'clipboard';
const btnCopy = new Clipboard('btn');
this.copyValue = 'hello world'; Copy after login
Event Sometimes we need to do something after copying, then we need the support of callback function. <p>Add the following code to the processing function: <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 class="btn" :data-clipboard-text="copyValue">点我复制</button>
e.clearSelection(); // 清除选中内容
});
// 复制失败后执行的回调函数
clipboard.on('error', function(e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
}); Copy after login
Summary The document also mentions that if <p>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.
<p>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 <p>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 <p>editable region. Definition bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument) The method returns a <p>Boolean value, indicating whether the operation was successful.
<p>aCommandName: Represents the command name, such as:
copy,
cut, etc. (see commands for more commands);
<p>aShowDefaultUI: Whether to display the user interface, usually
false;
<p>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> Copy from the input box using
Now there is an <p><input> on the page tag, we want to copy the content, we can do this:
<input id="demoInput" value="hello world">
<button id="btn">点我复制</button> Copy after login
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 after login
Copy elsewhere Sometimes there is no <p><input>## on the page # tag, we may need to copy the content from a <p>
, or copy the variable directly.
Remember in the definition of the execCommand()<p> method that it can only operate editable areas
, which means that except and <textarea>. <code>
At this time we need to save the country.
<button id="btn">点我复制</button> Copy after login
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);
}) Copy after login
<p> It can be regarded as a successful curve to save the country. Several pitfalls were encountered when using this method.
<p>Pits Encountered
When debugging under Chrome, this method ran perfectly. Then when it came to debugging the mobile terminal, the pit came out.
<p>Yes, that’s right, it’s you, ios. . .
<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.
<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');<p> to the code to make this<input>
is read-only, so the keyboard will not be pulled up.
Cannot copy<p>这个问题是由于 input.select()
在ios下并没有选中全部内容,我们需要使用另一个方法来选中内容,这个方法就是 input.setSelectionRange(0, input.value.length);
。
<p>完整代码如下:
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);
}) Copy after login
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!