原生js实现浏览器复制
document.execCommand()
浏览器中点击按钮去实现复制我们想要的内容,现在常见的方法主要是两种,一种是第三方库clipboard.js 但是引入一个库也是要考虑加载成本的,另一种就是今天要介绍的 document.execCommand();几乎兼容所有的现在浏览器。
实现代码
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>浏览器复制</title>
- </head>
- <body>
- <div class="container">
- <span id="copy-txt" class="txt">这是要复制的文本</span>
- <button onclick="handleCopyToClipboard(document.getElementById('copy-txt'))">点击复制</button>
- </div>
- <script>
- function handleCopyToClipboard(copyWord) {
- var range = document.createRange();
- range.selectNode(copyWord);
- window.getSelection().removeAllRanges();
- window.getSelection().addRange(range);
- document.execCommand('copy');
- alert('复制成功');
- window.getSelection().removeAllRanges();
- }
- </script>
- </body>
- </html>
参考地址:Document.execCommand() - Web APIs | MDN (mozilla.org)
示例:
这是要复制的文本https://hooper.eu.org
THE END
二维码
打赏

共有 0 条评论