At the beginning, there was no content accessible to clipborad on the web. In the past, we could only use flash if we wanted to perform copy/paste/cut. But now, the great H5 or W3C has launched a draft on H5 control clipboard. The most famous are the two APIs:
document.execCommand() ClipboardEvent
Let’s learn about them step by step. Let’s first look at the use of classic execCommand.
Copy operation
input copy
We need to understand the basic copy process first:
select
Copy (command + c || ctrl + c)
execCommand also follows this process to achieve this effect. If we want to use execCommand to perform copy, we should first select the element you want to copy.
Here, a new API, window.getSelection(), will also be used. Specifically:
getSelection(): used to obtain the content of the currently selected element. Generally speaking, you use the mouse to select the content on the page.
toString(): Used to directly change the selected content into text.
The basic usage is:
//Output the selected text
window.getSelection().toString();
We generally only use this API for auxiliary functions. The most common approach is to dynamically create input elements and then dynamically specify input[value]. Execute select(), select, and then execute copy.
# The total code is
function copyContent(elementId) { // 动态创建 input 元素 var aux = document.createElement("input"); // 获得需要复制的内容 aux. set Attribute("value", document.getElementById(elementId).innerHTML); // 添加到 DOM 元素中 document.body.app end Child(aux); // 执行选中 // 注意: 只有 input 和 textarea 可以执行 select() 方法. aux.select(); // 获得选中的内容 var content = window.getSelection().toString(); // 执行复制命令 document.execCommand("copy"); // 将 input 元素移除 document.body.removeChild(aux); }
Look at an example
Copy as you like
Of course, if you don’t want to add input elements dynamically, think What should I do if I copy the specified DOM element directly? Here you need to use HTML5's newly provided createRange() related methods. Of course, getSelection() above is also one of them. The APIs used are:
document.createRange(): used to create a selected container. Returns a range Object. The compatibility of this API is also very good, and is supported by both mobile phones and PCs.
selectNode(DOM): Returns the method mounted on the range Object. Used to add selected elements. Only one
window.getSelection()
addRange(range) can be added: This method is mounted under the getSelection() method and is used to perform element selection. (! Very important)
That’s all the API above:
Just look at the demo
Here, I’ll post the key code:
var copyDOM = document.querySelector('#selector'); var range = document.createRange(); // 选中需要复制的节点 range.selectNode(copyDOM); // 执行选中元素 window.getSelection().addRange(range); // 执行 copy 操作 var successful = document.execCommand('copy'); try { var msg = successful ? 'successful' : 'unsuccessful'; console.log('copy is' + msg); } catch(err) { console.log('Oops, unable to copy'); } // 移除选中的元素 window.getSelection().remove All Ranges();
Required here As an additional reminder, the above copy operation cannot be performed automatically. That is, interactive behaviors such as copy cannot be performed without any user interaction. Therefore, click event is needed here to assist (of course, you can also use other events instead).
Use clipboard to copy
First of all, clipboard was proposed recently, so its compatibility still needs time to be verified. The current compatibility is to support some simple events.
If your browser supports ClipboardEvent Constructor. Then the copy operation becomes extremely simple.
// Of course, the following code should be placed in the click event of an interaction.
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 the document to set or obtain relevant information. We obtain the clipboardData object can only be achieved through event callbacks:
e.clipboardData: can only be obtained through the copy/paste/cut event on the document
document.addEvent List ener('copy', function(e){ // 设置信息,实现复制 e.clipboardData.setData('text/plain', 'Hello, world!'); e. prev entDefault(); });
clipboardData : This obj also mounts two commonly used API
format: which is the basic MIME type. The most commonly used one is text/plain. For specific content, please refer to MIME references
data: It is the specific data content put in corresponding to the MIME type
setData(format, data): Set related data information, mainly used for copy and cut in related events.
getData(format): Generally used in paste events. Used to get the contents of the clipboard. However, you need to set the correct decoding format (that is, set the correct MIME type). Also, this method can only be used in the paste event.
The above feels like a brief introduction to the API, and then I will formally talk about some practical information. If you use clipboardData to implement custom copy content. In this way, you can not only copy the simple text on the page, but also copy imagesinformation, etc.
Look at the code
// Bind interactive events on the specified DOM
DOM.addEventListener('click',function(){},false){ // 添加 copy 内容 document.addEventListener('copy',function copy (e) { msg = `<${msg}/>`; e.clipboardData.setData('text/plain', msg); e.preventDefault(); }) // 执行 copy 命令 document.execCommand('copy'); // 移除绑定事件 document.removeEventListener('copy','copy'); }
cut && paste Related
The front looks quite simple of. Of course, some students may think, aren’t there other events such as cut and paste? Is it possible to do the same?
Um...
At first, I thought so too, but reality often gives you a gentle caress. Because, in order to prevent you from maliciously obtaining user information, in Chrome, generally speaking, you cannot trigger the paste event through document.execCommand('paste'). However, in the mobile version, the rule is that you can trigger cut and paste in editable elements, but copy can only be triggered in valid selected elements.
根据上面的说法,我们可以通过利用 paste 的相关方法,来具体应用到实践中。比如,防止用户粘贴信息。这特别适用于那些做题页面,防止你查资料然后 copy 相关答案。
document.addEventListener('paste',function copy (e) { e.preventDefault(); }); 当然,还有更狠的,直接禁止 copy,paste,cut 事件。 ['cut', 'copy', 'paste'].forEach((event)=>{ document.addEventListener(event, (e)=>{ e.preventDefault(); });});
方案总结
HTML5 现在能完美提供给我们的应该就是 copy 事件的使用,对于市面上的 clipboard.js 差不多也是运用上述的知识点。根据上面的描述,可以了解到,想要实现复制功能有三种渐进退化方案。以下兼容性由高到低:
input 模式
createRange
clipboard 直接操作
现在 React 比较火,这里我简单的写了一个 copybtn 组件。具体的使用 README 已经写清楚了,如果有什么不懂的地方可以 @我。
【相关推荐】
1. 免费h5在线视频教程
2. HTML5 完整版手册
The above is the detailed content of H5 copy operation example code. For more information, please follow other related articles on the PHP Chinese website!