search
HomeWeb Front-endH5 TutorialH5 copy operation example code

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(&#39;text/plain&#39;, msg);
            e.preventDefault();
        })
    // 执行 copy 命令
    document.execCommand(&#39;copy&#39;);
    // 移除绑定事件
    document.removeEventListener(&#39;copy&#39;,&#39;copy&#39;);
}

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(&#39;paste&#39;,function copy (e) {            e.preventDefault();        });
当然,还有更狠的,直接禁止 copy,paste,cut 事件。
[&#39;cut&#39;, &#39;copy&#39;, &#39;paste&#39;].forEach((event)=>{    document.addEventListener(event, (e)=>{        e.preventDefault();    });});

方案总结

HTML5 现在能完美提供给我们的应该就是 copy 事件的使用,对于市面上的 clipboard.js 差不多也是运用上述的知识点。根据上面的描述,可以了解到,想要实现复制功能有三种渐进退化方案。以下兼容性由高到低:

input 模式

createRange

clipboard 直接操作

现在 React 比较火,这里我简单的写了一个 copybtn 组件。具体的使用 README 已经写清楚了,如果有什么不懂的地方可以 @我。

【相关推荐】

1. 免费h5在线视频教程

2. HTML5 完整版手册

3. php.cn原创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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)