JS realize functions of pasteboard

Today at JS copy of sharing with you the contents of the clipboard into knowledge.

1 implements functions pasteboard

Using the Clipboard is an essential skill. As agricultural code should know, Tab, Ctrl / Cmd + A, Ctrl / Cmd + C and Ctrl / Cmd + V are autofocus, copy, paste shortcut keys.

The average user may be less easy. Even if the user knows what the clipboard is (in addition to) those who have an excellent eye contact or react quickly, in other cases it is difficult to highlight the exact text they want. If the user does not know the keyboard shortcuts you do not see the hidden Edit menu, or right-click menu never used or do not know the long press touch-screen pop-up menu of options, then he is probably not aware replication.

Should we provide a "Copy to Clipboard" button to help you? This feature should be useful, even for people familiar with the shortcuts users.

About clipboard security
a few years ago, the browser can not directly use the clipboard. Developers had to be implemented by Flash.

Clipboard seem insignificant, but imagine if the browser can freely view and manipulate the content, what will happen. JS script (including third-party scripts) can view the text in the clipboard information, and passwords, sensitive information and even send the entire document to a remote server.

Limited now clipboard basic functions, with the following restrictions:
Most browsers support the clipboard, except Safari. (Annotation, Safari is already supported)
support varies depending on the browser, some features are incomplete or there is a problem.

Events must be initiated by the user, such as clicking the mouse or pressing keyboard. Scripts can not freely access the clipboard.

document.execCommand ()
This method is the key to the clipboard, it can pass cut, copy, paste three kinds of parameters. The most commonly used document.execCommand ( 'copy') began to introduce.

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

But in Chrome, although Chrome does support the use of copy named, but two methods return false. So it is best to check the code packets in a try-catch block.

Next, we should allow the user to copy what is it? You must highlight the text, all browsers are available for select () method to select the text in the text input and textarea. While Firefox and Chrome / Opera supports document.createRange method which allows to select text 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.

clipboard.js
If you do not want to own implementation of a more robust cross-browser clipboard method, then, clipboard.js can help you. There are several ways to set options, such as H5 data property, set binding targets trigger elements and elements such as:

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

Yourself achieve
clipboard.js size only 2Kb, if only partially implement the following function, then we can achieve in 20 lines of code:

Form elements can be only partially replicated

If that does not support browser (yes, that means that Safari) (Annotation, Safari is already supported), highlight the selected text, and prompts the user to press Ctrl / Cmd + C.

Like clipboard.js like to create a button for triggering method, which has a data attribute data-copytarget, pointing to copy the elements (ie #website)

<input type="text" id="website" value="http://www.sitepoint.com/" />
<button data-copytarget="#website">copy</button>

Now perform a function expression click event binding function, which function is used to parse data-copytarget content attributes, and select the text field corresponding to perform document.execCommand ( 'copy') ,. If failed, the text remains selected, display the prompt box:

(function() {
  'use strict';
  // click events  
  document.body.addEventListener('click', 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('copy');        
      inp.blur();      }      
      catch (err) {        
      alert('please press Ctrl/Cmd+C to copy');      }
    }  }})();

Example Address: https://codepen.io/SitePoint/pen/vNvEwE/

Although in the embodiment, styles and animations count code, the code has more than 20 lines, but the style of animation, and are optional.

Summary:
() Select the contents of the form elements to be copied by .select

Call document.execCommand ( "copy") method

Call .blur () method, the focus is removed from the form elements

Steps 2 and 3 in the first package try catch block, without prompting supported browser

Otherwise
there are many new clipboard application mode. For example Trello.com, when hovering over the card, press Ctrl / Cmd + C card and copy the link address to the clipboard. Way behind its implementation are: create a hidden form element that contains the URL, and then select and copy its contents. Very clever and practical - I suspect that few users know this feature!

About JS achieve the Clipboard function, you learn how much? Comments are welcome in the comments area!

Published 180 original articles · won praise 13 · views 7169

Guess you like

Origin blog.csdn.net/weixin_45794138/article/details/104883270