个性化阅读
专注于IT技术分析

如何使用JavaScript将文本轻松复制到剪贴板

本文概述

自动复制到剪贴板可能很危险, 因此大多数浏览器都很难做到这一点。任何人都不想以剪贴板中的可疑链接或可能使我们陷入困境的事情结束。

你在互联网上可以找到的任何可行的解决方案都需要通过用户的动作(例如点击)来触发。没有任何解决方案, 即使使用Flash也可以自动复制内容, 而无需用户交互。这就是你需要了解的与Javascript或Flash中的剪贴板相关的所有信息。

在这篇文章中, 我们将为你提供使用纯JavaScript轻松完成此任务的不同方法, 如果你无法实现, 则将找到使用Flash作为具有清晰实现方式的后备解决方案。

Java脚本

1. execCommand

第一个实现使用文档execCommand函数。以下浏览器支持此功能:

  • IE10。
  • 谷歌浏览器> = 43。
  • Mozilla Firefox> = 41。
  • 歌剧> = 29。

技巧很简单, execCommand会将textarea内的文本本地复制到剪贴板。

重要

如果操作不是由用户触发的, 则该代码将永远无法工作(仅单击)。通过控制台注入将不起作用。请注意, 文本区域需要可见(display:none)将使代码失败。

function setClipboardText(text){
    var id = "mycustom-clipboard-textarea-hidden-id";
    var existsTextarea = document.getElementById(id);

    if(!existsTextarea){
        console.log("Creating textarea");
        var textarea = document.createElement("textarea");
        textarea.id = id;
        // Place in top-left corner of screen regardless of scroll position.
        textarea.style.position = 'fixed';
        textarea.style.top = 0;
        textarea.style.left = 0;

        // Ensure it has a small width and height. Setting to 1px / 1em
        // doesn't work as this gives a negative w/h on some browsers.
        textarea.style.width = '1px';
        textarea.style.height = '1px';

        // We don't need padding, reducing the size if it does flash render.
        textarea.style.padding = 0;

        // Clean up any borders.
        textarea.style.border = 'none';
        textarea.style.outline = 'none';
        textarea.style.boxShadow = 'none';

        // Avoid flash of white box if rendered for any reason.
        textarea.style.background = 'transparent';
        document.querySelector("body").appendChild(textarea);
        console.log("The textarea now exists :)");
        existsTextarea = document.getElementById(id);
    }else{
        console.log("The textarea already exists :3")
    }

    existsTextarea.value = text;
    existsTextarea.select();

    try {
        var status = document.execCommand('copy');
        if(!status){
            console.error("Cannot copy text");
        }else{
            console.log("The text is now on the clipboard");
        }
    } catch (err) {
        console.log('Unable to copy.');
    }
}

玩以下小提琴:

2.使用Clipboard.js

每个人都喜欢图书馆, 你应该也喜欢图书馆。库使你的一切变得更轻松, 并且它已经过许多人的测试。 Clipboard.js是一些漂亮的库之一, 只需几行代码, 它们便可以帮助你实现目标。 Clipboard.js是一种无需Flash即可将文本复制到剪贴板的现代方法, 它没有依赖项, 而且轻巧。

要初始化剪贴板.js, 请使用以下代码:

<button class="btn" data-clipboard-text="Este texto sera copiado">Copiar texto</button>

<script>
var clipboard = new Clipboard('.btn');

clipboard.on('success', function(e) {
    console.info('Accion:', e.action);
    console.info('Texto:', e.text);
    console.info('Trigger:', e.trigger);

    e.clearSelection();
});

clipboard.on('error', function(e) {
    console.error('Accion:', e.action);
    console.error('Trigger:', e.trigger);
});
</script>

剪贴板构造函数期望将dom选择器作为第一个参数。在这种情况下, 所有btn类的项目都将文本复制到剪贴板中。该库也依赖execCommand。

带有Flash的后备广告

如果你确实需要在网站上实现此功能并为旧的浏览器提供支持, 则除了使用Flash提供后备功能外, 你别无选择。

但是不必担心会使你的代码混乱, 你可以使用ZeroClipboard实施干净的解决方案。在此访问可访问该插件首页的演示, 该示例可正常运行。

但是, 该解决方案也不是没有限制。由于浏览器和Flash安全性的限制, 仅当用户单击不可见的Flash电影时, 才会发生剪贴板注入。来自JavaScript的模拟点击事件不足, 因为这将导致剪贴板中毒。

ZeroClipboard的实现非常简单:

<!DOCTYPE html>
<html>
 <head>
 <!-- Get a copy of ZeroClibboard.js in the official repository 
      Note that the .swf core file needs to be in the same path that .js file
      The flash file will be automatically loaded by the plugin.
 -->
 <script src="ZeroClipboard.js"></script>
 </head>
 <body>
 <button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button>
 <script>
    var client = new ZeroClipboard( document.getElementById("copy-button") );
    // Wrap the events inside the ready event of the swf clipboard
    client.on( "ready", function( readyEvent ) {
        // alert( "ZeroClipboard SWF is ready!" );

        client.on( "aftercopy", function( event ) {
           // `this` === `client`
           // `event.target` === the element that was clicked
           event.target.style.display = "none";
           alert("Copied text to clipboard: " + event.data["text/plain"] );
        });
    });
 </script>
 </body>
</html>

玩得开心 !

赞(0)
未经允许不得转载:srcmini » 如何使用JavaScript将文本轻松复制到剪贴板

评论 抢沙发

评论前必须登录!