Giter Club home page Giter Club logo

Comments (1)

shfshanyue avatar shfshanyue commented on May 15, 2024

它一般可以使用第三方库 clipboard-copy 来实现,源码很简单,可以读一读

目前最为推荐的方式是使用 Clipboard API 进行实现

navigator.clipboard.writeText(text)

而对于一些不支持 Clipboard API 的浏览器,使用以下 API 进行复制

  1. 选中: Selection API
  2. 复制: document.execCommand (已被废弃)

选中: Selection API/Range API

选中主要利用了 Selection API 与 Range API

选中的代码如下

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

// RangeAPI: 制造区域
range.selectNodeContents(element);

// Selection: 选中区域
selection.addRange(range);

selectedText = selection.toString();

取消选中的代码如下

window.getSelection().removeAllRanges();

它有现成的第三方库可以使用: select.js

复制: execCommand

复制就比较简单了,execCommand

document.execCommand('copy')

from daily-question.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.