In some blogging systems, such as digger’s blog, it is possible to copy code, how does it work

【Q019】 How to implement the function of selected copy

It can generally be implemented using the third-party library clipboard.js, the source is very simple, you can read

There are two main points

  1. The selected
  2. copy

The selected

The Selection takes advantage of the Selection API

The selected code is shown below

const selection = window.getSelection();
const range = document.createRange();

range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);

selectedText = selection.toString();
Copy the code

The unchecked code is shown below

window.getSelection().removeAllRanges();
Copy the code

It has a third-party library ready to use: select.js

copy

Copying is easy, execCommand

document.exec('copy')
Copy the code

Study such as spring from the seedlings, see its increase, day has a director. So I created a github repository with at least one question per day. Full stack, GraphQL, Devops, microservices, and soft skills for career growth.