search
HomeWeb Front-endJS TutorialJS implements pasteboard copy function code sharing
JS implements pasteboard copy function code sharingFeb 06, 2018 pm 02:11 PM
javascriptcodeFunction

Using the clipboard is an essential skill. As a coder, everyone should know that Tab, Ctrl/Cmd + A, Ctrl/Cmd + C and Ctrl/Cmd + V are shortcut keys for auto-focus, copy and paste respectively.

But it may not be easy for ordinary users. Even if a user knows what a clipboard is, it will be difficult to highlight the exact text they want (except for) those with great eyesight or quick reflexes. If the user doesn't know the keyboard shortcuts, can't see the hidden editing menu, has never used the right-click menu, or doesn't know that long-pressing the touch screen brings up the options menu, then he will probably not be aware of the copy function.

So should we provide a "Copy to Clipboard" button to help the user? This feature should be useful even for users who are very familiar with keyboard shortcuts.

About clipboard security

A few years ago, it was impossible for browsers to use the clipboard directly. Developers had to implement it through Flash.

The clipboard may seem inconsequential, but imagine what would happen if the browser could see and manipulate the content at will. JS scripts (including third-party scripts) can view the text information in the clipboard and send passwords, sensitive information, or even entire documents to the remote server.

The current clipboard has limited basic functions and has the following restrictions:

  1. Most browsers support the clipboard, except Safari.

  2. Support varies by browser, and some features are incomplete or problematic.

  3. Events must be initiated by the user, such as clicking the mouse or pressing the keyboard. The script does not have free access to the clipboard.

document.execCommand()

This method is the key to implementing the clipboard, it can pass in cut, copy, paste three parameters. Let’s start with the most commonly used document.execCommand('copy').

Before using, we should check whether the browser supports the copy command: document.queryCommandSupported('copy'); or document.queryCommandEnabled('copy'); , these two methods have the same effect.

But under Chrome, although Chrome does support the use of copy naming, both methods return false. So it's better to wrap the checking code in a try-catch block.

Next step, what should we allow users to copy? Text must be highlighted, and all browsers can use the select() method to select text within text input and textarea. At the same time, Firefox and Chrome/Opera also support the document.createRange method, which allows text selection from any element, as follows:


// select text in #myelement node
  var
   myelement = document.getElementById('#myelement'),
   range = document.createRange();
  range.selectNode(myelement);
  window.getSelection().addRange(range);

But IE/ Edge does not support it.

clipboard.js

If you don’t want to implement a more robust cross-browser clipboard method yourself, clipboard.js can help you. It has several ways to set options, such as H5's data attribute, setting binding trigger elements and target elements, such as:


<input id="copyme" value="text in this field will be copied" />
<button data-clipboard-target="#copyme">copy</button>

Do it yourself

The size of clipboard.js is only 2Kb. If only some of the following functions are implemented, it can be implemented within 20 lines of code:

Only some form elements can be copied

If in an unsupported browser (yes, Safari), you can highlight the selected text and prompt the user to press Ctrl/Cmd + C.

Like clipboard.js, first create a button to trigger the method. It has a data attribute data-copytarget, pointing to the element to be copied (i.e. #website)


<input type="text" id="website" value="http://www.sitepoint.com/" />
<button data-copytarget="#website">copy</button>
一个立即执行函数表达式绑定click事件的函数,该函数用于解析 data-copytarget 属性内容,选择对应字段的文本并执行 document.execCommand(&#39;copy&#39;) ,。若失败,文本保持选中状态,显示提示框:
(function() {
 &#39;use strict&#39;;
 // click events
 document.body.addEventListener(&#39;click&#39;, copy, true);
 // event handler
 function copy(e) {
  // find target element
  var
   t = e.target,
   c = t.dataset.copytarget,
   inp = (c ? document.querySelector(c) : null);
  // is element selectable?
  if (inp && inp.select) {
   // select text
   inp.select();
   try {
    // copy text
    document.execCommand(&#39;copy&#39;);
    inp.blur();
   }
   catch (err) {
    alert(&#39;please press Ctrl/Cmd+C to copy&#39;);
   }
  }
 }
})();

Example

Although in the above example, including the code for styles and animations, the code has exceeded 20 lines, animations and styles are optional.

Summary:

  1. Select the content of the form element to be copied through .select()

  2. Call document.execCommand( "copy") method

  3. Call the .blur() method to remove focus from the form element

  4. Include steps 2 and 3 In the try catch block, if the browser does not support it, it will prompt

Other ways

There are many novel clipboards Application method. For example, Trello.com, when hovering over a card, you can press Ctrl / Cmd + C and copy the card's link address to your clipboard. The implementation behind it is to first create a hidden form element containing the URL, then select and copy its content. Very clever and useful - I suspect very few users know about this feature!

Related recommendations:

js implements the function code of copying to the pasteboard_basic knowledge

JavaScript implements the code of copying content to the pasteboard _javascript skills

js method of clicking on an image to copy the image address to the pasteboard_javascript skills

The above is the detailed content of JS implements pasteboard copy function code sharing. 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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools