This is the 11th day of my participation in Gwen Challenge
One key copy idea
- Prepare the content to be copied
- Use the Clipboard API to write directly to the Clipboard, or use document.execcommand () to manipulate the selected content. You need to build a hidden input box, place the content in the input box, and then select it
Clipboard API
According to MDN:
Clipboard The Clipboard API provides the ability to respond to Clipboard commands (cut, copy, and paste) with asynchronous reads and writes to the system Clipboard. Access to clipboard content after obtaining Permissions from the Permissions Permissions API; Clipboard content is not allowed to be read or changed if the user has not granted permission.
The Clipboard API adds the read-only property Clipboard to the Navigator interface, which returns a Clipboard object that can read and write the contents of the Clipboard. In Web applications, the clipboard API can be used to cut, copy, and paste.
Asynchronous clipboard read-write methods can only be used if the user has previously granted the site or application permission to access the clipboard. Permissions must be obtained by obtaining the “Clipboard-read” and/or “clipboard-write” items of the Permissions API.
Method of use
methods | instructions |
---|---|
read | Reads data (such as an image) from the clipboard and returns a Promise object |
readText | Read the text and return a Promise object |
write | Writes data (such as an image) to the clipboard and returns a Promise object |
writeText | Write text and return a Promise object |
document.execCommand()
Method of use
function copy(e) {
// Build a hidden input
let transfer = document.createElement('input');
document.body.appendChild(transfer);
transfer.value = target.value; // This represents what you want to copy
// First focus, then select
transfer.focus();
transfer.select();
// Perform the replication operation
if (document.execCommand('copy')) {
document.execCommand('copy');
}
// Copy successfully, clean up the site
transfer.blur();
document.body.removeChild(transfer);
}
// Bind to the click event
$('#copyBtn').addEventListener('click', copy);
Copy the code
Finally, the third party library clipboard.js is recommended
Clipboard. js is a copy and paste library that is only 3KB in size.