“This is the 10th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.
I haven’t written front-end code for a long time. Recently, when I completed a Chrome plugin, I wanted to save data to the paste version. I tried several ways, but found that none of them worked well. As a front-end rookie can only obscene a bit of implementation
Here is a JS implementation of writing text to a stickboard
/** * writes to the paste board */
function toCopy(text) {
// Force the passed argument to a string
text = String(text);
input = document.createElement('INPUT');
input.style.opacity = 0;
input.style.position = 'absolute';
input.style.left = '-9999px';
document.body.appendChild(input);
input.value = text;
input.select();
input.setSelectionRange(0, text.length);
document.execCommand('copy');
document.body.removeChild(input);
}
Copy the code
The basic idea can be understood from the above implementation:
- Create an invisible input
- Then copy the text to the input
- Then use
document.execCommand
To realize the copy function - Finally, remove the input