This is the fourth day of my participation in the August Text Challenge.More challenges in August
“Copy and paste” is a magic skill we often use in the daily development process of siege lion code, but have you ever thought that the browser can help us to implement copy and paste operations, greatly increase our time.
In the business requirements, we encounter the demand to actively assist users to copy and paste. We need to actively copy data through JS to assist users to carry out other operations
Read this article and you will learn
- How to implement automatic front end copy-and-paste in native or third-party mode
- How to automatically add original author information to copied information
copy
Implemented with native JS
- Replication can be done through the Document object
document.execCommand('copy')
- Compatibility with this syntax can be found here
- An example is already provided in the official API; this article shows only one example in vUE
- Ideas:
- Dynamically bind variables
- Is a hidden input field
- Gets the value of the input box
- Call the official API for replication
<button @click="copyRoles"> </button> <input v-if="roles && roles.length" id="clipBoard" v-model="roles" style="position: absolute; opacity: 0;" > </input> //js part copyRoles() {let data = "if(this.roles && this.roles.length) {let spanSelect = Document.queryselector ('#clipBoard') spanSelect.select() If (document.execCommand('copy')) {document.execCommand('copy') console.log(' information copied successfully ')} else {document.execCommand('copy') console.log(' information copied successfully ')} else { Console. log(' Replication failed! ')}} else {console.log(' Copy failed! ')}}Copy the code
Updated native JS implementation (for mobile)
- Copying using native methods is done by selecting text, but using traditional methods
ele.select()
It will fail on the mobile terminal, so you need to perform compatibility processing on the mobile terminal.
If (document.querySelector('#orderId')) {let e = document.getelementById ('orderId') document.getElementById("clipBoard").removeChild(e) } let input = document.createElement('input') input.id = 'orderId' input.value = data input.readOnly = "readOnly" document.getElementById("clipBoard").appendChild(input) let eleSelect = document.querySelector('#orderId') this.selectText(eleSelect, 0, Item.length) if(document.execCommand('copy')) {document.execCommand('copy') this.$littleHint(' copy')} else {document.execCommand('copy') this. This.$littleHint(' failed ')} eleselect.blur ()}, // Select selectText(textbox, startIndex, stopIndex) { if (textbox.createTextRange) { const range = textbox.createTextRange() range.collapse(true) Range.movestart ('character', startIndex)// Start cursor range.moveEnd('character', StopIndex - end startIndex) / / the cursor range. The select ()} else {textbox. SetSelectionRange (startIndex, stopIndex) textbox.focus() } },Copy the code
Implemented by clipboard.js
-
installation
- Install through the NPM dependency package
npm install clipboard --save
- Import through CDN
< script SRC = "https://cdn.jsdelivr.net/npm/[email protected]/dist/clipboard.min.js" > < / script >
-
use
- To copy the contents of the current DOM node, simply be
data-clipboard-target
Property setting content.
<button class=" BTN "data-clipboard-text=" <img SRC =" XXX" Alt =" button ">Copy the code
- To set the content to be copied, simply set
data-clipboard-target
Property binding to the corresponding node.
<input id="clipTarget" value=" <button class=" BTN "data-clipboard-target="#clipTarget"> <img SRC =" XXX" Alt =" button ">Copy the code
data-clipboard-action
Set tocopyEvent orshearThe event
<input id="clipTarget" value=" <button class=" BTN "data-clipboard-action="cut" data-clipboard-target="#clipTarget"> <img SRC =" XXX" Alt =" copy "> </button>Copy the code
- To copy the contents of the current DOM node, simply be
paste
- There is no good plan for pasting. It is very poor compatibility to operate the pasting board with JS directly without users’ active operation. It is suggested to consider a reasonable plan to realize this function. Simply put: Change the demand!
Native JS implementation (poor compatibility, only supports IE and FF browsers)
- JavaScript’s clipboardData object provides three methods to access the stickboard
- ClearData (sDataformat): Deletes data in the specified format from the clipboard
- SetData (sDataformat,sData): Assigns data in the specified format to the clipboard, and returns true if the operation succeeds
- GetData (sDataformat): Gets data from the clipboard in the specified format
let text = "123"; if (! window.clipboardData.setData()) { return; } window. ClipboardData. SetData (' Text, Text) / / give the Text format of the data alert (" replication failed!" ); text = window.clipboardData.getData('Text'); // Get data in text format alert(text); window.clipboardData.clearData('Text'); / / remove the text format of the data text = window. The clipboardData. GetData (" text "); alert(text);Copy the code
A roundabout way
- The user actively triggers the Paste event (in three ways)
- Press CTRL + V
- Select “Paste “from your browser’s edit menu
- Right click the mouse button and select “Paste “from the context menu.
- Through these three approaches, our solution has two main aspects
- An active prompt directs the user to copy the contents of the clipboard into an input box, or a Textarea, to retrieve the value.
window.addEvent("paste",function(e){ });
By listening to events, listen to the user’s paste operation, so as to get the data you want
How do I modify the contents on the user paste board
When we copy information in a lot of websites, we can find that many websites automatically add the information of the original author in the copied information, so how to do the following operation is, of course, and the part of the paste board mentioned above.
<! --> copydom.bind ({copy: function (event) { var clipboardData = event.originalEvent && event.originalEvent.clipboardData || window.clipboardData; if (! clipboardData) { return; } var copyText = window.getSelection().toString(); if (copyText) { event.preventDefault(); Clipboarddata.setdata ('text/plain', copyText + 'modify the contents of the paste '); } return false; }});Copy the code
Write in the last
If you find this article beneficial to you, please like it and share it with more people who need it!
Welcome to pay attention to “Quanzhandao road” and wechat official account “Quanzhandao Road”, get more good articles and free books!
If you need [Baidu] & [Bytedance] & [JINGdong] & [Ape Tutoring], please leave a message, you will enjoy VIP speed push service ~
Past oliver
Create a personalized Github profile
The interviewer asks you<img>
What would you say about the element
Special JS floating-point number storage and calculation
Long [word] baidu and good interview after containing the answer | the nuggets technology essay in the future
Front end practical regular expression & tips, all throw you 🏆 nuggets all technical essay | double festival special articles
A detailed explanation of the unpopular HTML tabIndex
A few lines of code teach you to solve the wechat generated posters and two-dimensional code
Principle of Vue3.0 Responsive data: ES6 Proxy
Make the interviewer fall in love with you
How to draw a fine line gracefully
[3 minutes] Front-end performance optimization -HTML, CSS, JS parts
Front-end performance Optimization – Page loading speed optimization
Front-end Performance Optimization – Network transport layer optimization