17611538698
webmaster@21cto.com

使用JS实现复制剪贴板功能

资讯 0 2954 2021-06-14 10:26:21
<p><img alt="" src="https://www.21cto.com/uploads/images/js.png" style="width: 950px; height: 490px;" /></p> <p>在本文中,我们将了解如何在网站上实现复制到剪贴板功能。即单击Copy按钮后,段落标签的内容/文本应复制到系统剪贴板,用户可以将其粘贴到系统中的任何位置。</p> <p>我们直接跳到代码部分。本文假设您对 HTML、JavaScript 和 DOM 操作有一些基本的了解。</p> <p><strong>代码</strong></p> <p><br /> 我们将编写一个非常简单的 HTML 页页来显示段落内容以及一个复制按钮。</p> <p>index.html</p> <pre> <code class="language-xhtml">&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt;     &lt;meta charset="UTF-8"&gt;     &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;     &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;     &lt;title&gt;Copy To Clipboard&lt;/title&gt; &lt;/head&gt; &lt;body align="center"&gt;     &lt;p id="content"&gt;The text to be copied.&lt;/p&gt;     &lt;button id="copy"&gt;Copy Text&lt;/button&gt;     &lt;script src="./script.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> <p><br /> script.js</p> <pre> <code class="language-javascript">// Reference of the paragraph tag const content = document.getElementById("content"); // Reference of the copy button const copyBtn = document.getElementById("copy"); // Copy button's onclick handler copyBtn.onclick = copyToClipboard; // Method responsible for copying the content function copyToClipboard() {     navigator.clipboard         .writeText(content.innerText)         .then(() =&gt; alert("Copied to clipboard"))         .catch((e) =&gt; alert(e.message)); } </code></pre> <p><br /> 所以首先我们获取段落标签和copy复制按钮,然后将onclick处理程序分配给copy按钮。</p> <p>单击copy按钮时,copyToClipboard方法将被调用。</p> <p><strong>复制到剪贴板</strong></p> <p><br /> 在copyToClipboard方法中,我们使用了HTML5的剪贴板 API(Clipboard API)。</p> <p>Clipboard API 可用于在 Web 应用程序中实现剪切、复制和粘贴功能。</p> <p>系统剪贴板通过全局navigator.clipboard属性公开。</p> <p>writeText剪贴板对象的方法需要一个字符串值作为参数,它将被写入剪贴板。</p> <p>它返回一个promise,一旦剪贴板的内容更新,该promise就会解决。如果出现任何一种错误,promise将被拒绝。</p> <pre> <code class="language-javascript">... navigator.clipboard     .writeText(content.innerText)     .then(() =&gt; alert("Copied to clipboard"))     .catch((e) =&gt; alert(e.message)); ...</code></pre> <p><br /> inner text段落标签的 传递给writeText方法,如果promise得到解决,即文本已成功被复制。</p> <p>同样道理,我们来可以实现cut剪切功能。原理是将文本复制到剪贴板后,只需用空字符串覆盖段落标签的innerText即可。</p> <pre> <code class="language-javascript">navigator.clipboard     .writeText(content.innerText)     .then(() =&gt; {         // Overwriting with an empty string         content.innerText = "";         alert("Copied to clipboard");     })     .catch((e) =&gt; alert(e.message));</code></pre> <p><br /> 谢谢各位阅读,如果你喜欢这篇文章或觉得它有些帮助,请点赞👍</p> <p><br /> &nbsp;</p>

评论