使用FireFox,Safari和Chrome将文本复制/放置在剪贴板上 [英] Copy / Put text on the clipboard with FireFox, Safari and Chrome

查看:134
本文介绍了使用FireFox,Safari和Chrome将文本复制/放置在剪贴板上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Internet Explorer中,我可以使用clipboardData对象来访问剪贴板。如何在FireFox,Safari和/或Chrome中执行此操作?

In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?

推荐答案

现在有一种方法可以很容易地做到这一点现代浏览器使用

There is now a way to easily do this in most modern browsers using

document.execCommand('copy');

这将复制当前选定的文本。您可以使用

This will copy currently selected text. You can select a textArea or input field using

document.getElementById('myText').select();

为了不可见地复制文本,您可以快速生成一个textArea,修改框中的文本,复制它,然后删除textArea。在大多数情况下,这个文本区域甚至不会闪烁到屏幕上。

To invisibly copy text you can quickly generate a textArea, modify the text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen.

出于安全考虑,浏览器只允许您复制,如果用户采取某种行动(即单击按钮)。执行此操作的一种方法是将一个onClick事件添加到调用复制文本的方法的html按钮。

For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text.

一个完整的例子看起来像

A full example would look like

<html>
<head>
    <title>copy test</title>
</head>
<body>
    <button onclick="copier()">Copy</button>
    <textarea id="myText">Copy me PLEASE!!!</textarea>

    <script>
        function copier(){
            document.getElementById('myText').select();
            document.execCommand('copy');
        }
    </script>
</body>
</html>

这篇关于使用FireFox,Safari和Chrome将文本复制/放置在剪贴板上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆