【问题标题】:Copy / Paste content to and from clipboard using javascript使用 javascript 在剪贴板中复制/粘贴内容
【发布时间】:2011-05-13 18:56:40
【问题描述】:

我需要将内容复制到剪贴板的 javascript,并且用户应该能够从剪贴板访问内容。即有两个按钮复制和粘贴。当您单击复制按钮时,文本区域中的文本会说 textarea 内容被复制到剪贴板,当您单击粘贴按钮时,它应该被粘贴到其他一些文本区域中,或者如果可能的话,在编辑器中 (TinyMCE)。

【问题讨论】:

  • 幸运的是,您无法使用 javascript 访问用户剪贴板 - 但您为什么不简单地为此使用 javascript 变量(全局变量在大多数情况下是邪恶的,但在这里我会说它是正是你要找的东西)?

标签: javascript clipboard copy-paste


【解决方案1】:

没有使用 javascript 的良好/经过充分测试的解决方案,大多数解决方案仅适用于 IE

我使用 Flash 组件 Clippy 做了一次复制到剪贴板的功能,它非常易于使用。 您可以在 Github 上查看它的存储库,但它只会复制到剪贴板..

另一个管理剪贴板的好库,也是在 Flash 中,是ZeroClipboard

【讨论】:

  • 我同意,如果您想在不绑定到特定浏览器的情况下访问剪贴板,Flash 是唯一的选择。
【解决方案2】:

您可以使用此代码。如果有人从您的网站复制内容。

document.addEventListener('copy', (event) => {
  const pagelink = `\n\nRead more at: ${document.location.href}`;
  let copyText = document.getSelection();
  copyText = 'use website for read content';
  event.clipboardData.setData('text', copyText + pagelink);
  event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</h1>

【讨论】:

    【解决方案3】:

    一个简单的谷歌会返回给我这个代码...:-)

    <SCRIPT language="JavaScript">
    <!--
    function highlightmetasearch() {
        document.post.message.select(); document.post.message.focus();
    }
    function copymetasearch() {
        highlightmetasearch();
        textRange = document.post.message.createTextRange();
        textRange.execCommand("RemoveFormat");
        textRange.execCommand("Copy");
        alert("This post has been copied to your clipboard.\nIf this post is lost when you submit it you can easily repost it.\nAlways use this feature before posting!");
    }
        // -->
    </SCRIPT>
    

    【讨论】:

    • 这是特定于 IE 的,并且显然与您未链接到的一些更大的示例相关联。
    猜你喜欢
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    相关资源
    最近更新 更多