Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【Q019】浏览器中如何实现剪切板复制内容的功能 #20

Open
shfshanyue opened this issue Nov 9, 2019 · 1 comment
Open
Labels
html htlm 与 DOM 相关

Comments

@shfshanyue
Copy link
Owner

在一些博客系统,如掘金的博客中,可以复制代码,它是如何实现的

@shfshanyue shfshanyue added the html htlm 与 DOM 相关 label Nov 9, 2019
@shfshanyue
Copy link
Owner Author

shfshanyue commented Nov 9, 2019

它一般可以使用第三方库 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')

@shfshanyue shfshanyue changed the title 【Q019】如何实现选中复制的功能 【Q019】浏览器中如何实现剪切板复制内容的功能 May 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
html htlm 与 DOM 相关
Projects
None yet
Development

No branches or pull requests

1 participant