JS实现一键复制可以使用以下方法:
1、使用document.execCommand()方法实现复制:
|
1
2
3
4
5
6
7
8
|
function copyTextToClipboard(text) { var textarea = document.createElement("textarea"); textarea.value = text; document.body.appendChild(textarea); textarea.select(); document.execCommand("copy"); document.body.removeChild(textarea);} |
使用示例:
|
1
|
copyTextToClipboard("Hello World"); |
注意:该方法在一些浏览器中可能不被支持。
2、使用Clipboard API实现复制:
|
1
2
3
4
5
6
7
|
function copyTextToClipboard(text) { navigator.clipboard.writeText(text).then(function() { console.log("Text copied to clipboard"); }, function(err) { console.error("Failed to copy text to clipboard: ", err); });} |
使用示例:
|
1
|
copyTextToClipboard("Hello World"); |
注意:该方法需要浏览器支持Clipboard API。
3、使用document.execCommand()和Range对象实现复制:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
function copyTextToClipboard(text) { var range = document.createRange(); var selection = window.getSelection(); var textarea = document.createElement("textarea"); textarea.value = text; document.body.appendChild(textarea); range.selectNodeContents(textarea); selection.removeAllRanges(); selection.addRange(range); textarea.setSelectionRange(0, textarea.value.length); document.execCommand("copy"); document.body.removeChild(textarea);} |
使用示例:
|
1
|
copyTextToClipboard("Hello World"); |
