In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how to achieve H5 copy operation, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
At first, there was nothing on the Web side that had access to clipborad. In the past, we had to rely on flash to execute copy/paste/cut. But now, the great H5, or W3C, has released a draft of H5's manipulation of clipboard. The most famous are the two API:
Document.execCommand () ClipboardEvent
Let's learn about it step by step. Let's first take a look at the use of classic execCommand.
Copy operation
Input replication
We need to understand the basic replication process first:
Check (select)
Copy (command + c | | ctrl + c)
ExecCommand also follows this process to achieve this effect. If we want to use execCommand to execute copy, we should first select the element you want to copy.
Here, you will also use a new API, window.getSelection (). Specifically, it is:
GetSelection (): used to get the contents of the currently selected element. Generally speaking, it is to select the content on the page with the mouse.
ToString (): used to change the selected content directly into text text.
The basic use is:
/ / output selected text
Window.getSelection () .toString ()
We usually only use this API for auxiliary purposes. The most common practice is to dynamically create input elements, and then dynamically develop input [value]. Execute select (), select it, and then execute copy.
# the total code is
Function copyContent (elementId) {/ / dynamically create the input element var aux = document.createElement ("input"); / / get the content to be copied aux.setAttribute ("value", document.getElementById (elementId) [xss_clean]); / / add document.body.appendChild (aux) to the DOM element; / / execute the check / / Note: only input and textarea can execute the select () method. Aux.select (); / / get the selected content var content = window.getSelection (). ToString (); / / execute the copy command document.execCommand ("copy"); / / remove the input element from document.body.removeChild (aux);}
Look at an example.
Arbitrary copy
Of course, what should you do if you don't want to add the input element dynamically and want to specify the DOM element of the copy directly? Here you need to use the new createRange ()-related method provided by HTML5. Of course, getSelection () above is also one of them. The API used are:
Document.createRange (): used to create the selected container. Returns a range Object. The compatibility of the API is also good, and it is supported by both the mobile side and the PC side.
SelectNode (DOM): returns the mount method on range Object. Used to add selected elements. Only one can be added
Window.getSelection ()
AddRange (range): this method is mounted under the getSelection () method to perform the selection of elements. (! Very important)
There are only some of the API above:
Just watch demo.
Here, I'll post the key code:
Var copyDOM = document.querySelector ('# selector'); var range = document.createRange (); / / Select the node to be copied range.selectNode (copyDOM); / / execute the selected element window.getSelection (). AddRange (range); / / perform the copy operation var successful = document.execCommand ('copy'); try {var msg = successful? 'successful':' unsuccessful'; console.log ('copy is' + msg);} catch (err) {console.log (' Oops, unable to copy');} / / remove the selected element window.getSelection () .removeAllRanges ()
An additional reminder here is that the above copy operation cannot be performed automatically. That is, interactive behaviors such as copy cannot be performed without any user interaction. So, here you need to use the click event to assist (of course, you can also use other events instead).
Copy using clipboard
First of all, clipboard is proposed recently, so its compatibility still needs to wait time to verify, the current compatibility is to support some simple event.
If your browser supports ClipboardEvent Constructor. Then the replication operation becomes extremely simple.
/ / of course, the following code should be placed in an interactive click event.
Var copyEvent = new ClipboardEvent ('copy', {dataType:' text/plain', data:'My string'}); document.dispatchEvent (copyEvent)
If not, you can only use the event.clipboardData API returned in the copy event of document to set or get the relevant information. We can only get the clipboardData object through event callback:
E.clipboardData: can only be obtained through the copy/paste/cut event on document
Document.addEventListener ('copy', function (e) {/ / set information to copy e.clipboardData.setData (' text/plain', 'Hello, worldview'); e.preventDefault ();})
ClipboardData: this obj also mounts two commonly used API
Format: it's the basic MIME type. The most commonly used one is text/plain. For details, please refer to MIME references.
Data: the specific data content that is put into the MIME type.
SetData (format, data): sets relevant data information, which is mainly used in events related to copy and cut.
GetData (format): commonly used in paste events. Used to get the contents of clipboard. However, you need to develop the correct decoding format (that is, set the correct MIME type). Also, this method can only be used in paste events.
The above feeling is to briefly introduce API, and then formally say some practical information. If you use clipboardData to implement custom copy content. In this way, you can copy not only the simple text text on the page, but also the picture information and so on.
Look at the code.
/ / bind interactive events on the specified DOM
DOM.addEventListener ('click',function () {}, false) {/ / add copy content document.addEventListener (' copy',function copy (e) {msg = ``; e.clipboardData.setData ('text/plain', msg); e.preventDefault ();}) / / execute the copy command document.execCommand (' copy') / / remove the binding event document.removeEventListener ('copy','copy');}
Cut & & paste correlation
It looks pretty simple in front, too. Of course, some students will think, isn't there other events such as cut and paste? Is it possible to do the same?
Uh...
At first, I also think so, but the reality will often give you a gentle caress. Because, in order to prevent you from obtaining user information maliciously, in Chrome, generally speaking, you cannot trigger paste events through document.execCommand ('paste'). On the mobile side, however, the rule is that you can trigger cut and paste in editable elements, and copy only in valid selected elements.
According to the above, we can apply it to practice by using the relevant methods of paste. For example, prevent users from pasting information. This is especially true for those problem pages that prevent you from looking up the information and then copy the relevant answers.
Document.addEventListener ('paste',function copy (e) {e.preventDefault ();}); and, of course, even more ruthless, directly prohibit copy,paste,cut events. ['cut',' copy', 'paste'] .forEach ((event) = > {document.addEventListener (event, (e) = > {e.preventDefault ();});})
Scheme summary
What HTML5 can provide us perfectly now should be the use of copy events, and it is almost the same for clipboard.js on the market. According to the above description, you can see that there are three progressive degradation schemes that want to achieve replication. The following compatibility ranges from high to low:
Input mode
CreateRange
Clipboard direct operation
Now React is quite popular, here I simply write a copybtn component. The specific use of README has been written clearly, if there is anything you don't understand, you can @ me.
The above is all the contents of the article "how to copy H5". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.