Javascript 不使用 flash 将所选文本复制到剪贴板 - 必须跨浏览器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6300213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:10:30  来源:igfitidea点击:

Copy selected text to the clipboard WITHOUT using flash - must be cross-browser

javascriptjquerycopyclipboard

提问by Nick Brunt

I want to have a button which selects the text in a textareaand copies it to the clipboard. I can't seem to find any solutions which work in all browsers and don't use flash.

我想要一个按钮来选择 a 中的文本textarea并将其复制到剪贴板。我似乎找不到任何适用于所有浏览器且不使用 Flash 的解决方案。

Surely this is doable? I've seen it all over the place but I guess they use flash, which I really want to stay away from if possible as some people don't have it.

这肯定是可行的吗?我到处都看到它,但我想他们使用闪光灯,如果可能的话,我真的想远离它,因为有些人没有它。

This is what I have so far - it just selects the text:

这就是我到目前为止所拥有的 - 它只是选择文本:

function copyCode() {
  $("#output-code").focus();
  $("#output-code").select();
}

(The focus is not strictly necessary)

(重点不是绝对必要的)

回答by arc

execCommand('copy')

execCommand('复制')

There is a very new option. It is cross-browser but it will take time until everyone has updated their browser.

有一个非常新的选择。它是跨浏览器的,但在每个人都更新他们的浏览器之前需要时间。

It works by using the document.execCommand('copy');function. With this function you'll copy the select text. This will not only work with textareas but with every selected text on the webpage (like in span, p, div, etc.).

它通过使用该document.execCommand('copy');函数来工作。使用此功能,您将复制选择的文本。这不仅会为工作textarea秒,但与网页上的每一个选择的文本(如在spanpdiv等)。

Available in Internet Explorer 10+, Chrome 43+, Opera 29+ and Firefox 41+ (see execCommandcompatibility here).

适用于 Internet Explorer 10+、Chrome 43+、Opera 29+ 和 Firefox 41+(请参阅此处的execCommand兼容性)。

Example

例子

// Setup the variables
var textarea = document.getElementById("textarea");
var answer  = document.getElementById("copyAnswer");
var copy    = document.getElementById("copyBlock");
copy.addEventListener('click', function(e) {

   // Select some text (you could also create a range)
   textarea.select(); 

   // Use try & catch for unsupported browser
   try {

       // The important part (copy selected text)
       var ok = document.execCommand('copy');

       if (ok) answer.innerHTML = 'Copied!';
       else    answer.innerHTML = 'Unable to copy!';
   } catch (err) {
       answer.innerHTML = 'Unsupported Browser!';
   }
});
<textarea id="textarea" rows="6" cols="40">
Lorem ipsum dolor sit amet, eamsemper maiestatis no.
</textarea><br/>

<button id="copyBlock">Click to copy</button> <span id="copyAnswer"></span>
   

回答by Devin Burke

This answer, while accurate in 2011, is now considerably out of date. See arc's answer, or https://stackoverflow.com/a/30810322/489560

这个答案虽然在 2011 年是准确的,但现在已经过时了。参见 arc 的回答,或https://stackoverflow.com/a/30810322/489560



You must use the Flash add-in you do not want to use to automatically copy text to the client's clipboard. Browsers are designed like this because a website automatically modifying the client's clipboard without the aid of active-x components is a security concern. Note that active-x components are programs that run on the user's machine and, technically, require the user's consent to be installed. Considering that the Clipboard is an operating system component, be happy that web browsers don't allow websites to highHyman it by default.

您必须使用不想使用的 Flash 插件来自动将文本复制到客户端的剪贴板。浏览器是这样设计的,因为网站在没有 active-x 组件帮助的情况下自动修改客户端的剪贴板是一个安全问题。请注意,active-x 组件是在用户机器上运行的程序,从技术上讲,需要用户同意才能安装。考虑到剪贴板是一个操作系统组件,很高兴网络浏览器默认不允许网站劫持它。

If the user does not have Flash, has Flash disabled, or has active-x disabled, then he or she probably is paranoid about security and doesn't want you messing with his or her keyboard anyway. At that point, the user would be used to not having much automatic or script-based functionality in websites. It's best to not try to openly defy the wishes of the end user.

如果用户没有 Flash、禁用了 Flash 或禁用了 active-x,那么他或她可能对安全性有疑虑,并且无论如何都不希望您弄乱他或她的键盘。那时,用户将习惯于在网站中没有太多自动或基于脚本的功能。最好不要试图公开违背最终用户的意愿。

Please refer to the following Stack Overflow links:

请参考以下 Stack Overflow 链接:

  1. How do I copy to the clipboard in JavaScript?
  2. Cross Browser Flash Detection in Javascript
  1. 如何在 JavaScript 中复制到剪贴板?
  2. Javascript 中的跨浏览器 Flash 检测

The ultimate answer there is to use Zero Clipboard, which is a library that uses a small, invisible Flash movie and JavaScript to use clipboard functionality like you are wanting. The library is available here: https://github.com/zeroclipboard/zeroclipboardThe second link shows how to detect if Flash is disabled or not installed, which allows you to display a warning message like you would for JavaScript.

最终的答案是使用零剪贴板,这是一个使用小的、不可见的 Flash 电影和 JavaScript 的库,可以像您想要的那样使用剪贴板功能。该库在此处可用:https: //github.com/zeroclipboard/zeroclipboard第二个链接显示了如何检测 Flash 是否被禁用或未安装,它允许您像对 JavaScript 一样显示警告消息。

回答by Gabriel Gularte

Now we have Clipboard.jsby @zenorocha

现在我们有了@zenorocha 的Clipboard.js

To use it, download and call the script on your page.html (or install with bower or npm)

要使用它,请下载并调用 page.html 上的脚本(或使用 bower 或 npm 安装)

<script src="path_to_script/clipboard.min.js"></script>

Instantiate a new trigger on your script.js

在 script.js 上实例化一个新触发器

new Clipboard('.trigger');

And go there to see some examples of usage: http://zenorocha.github.io/clipboard.js/#usage

并去那里查看一些使用示例:http: //zenorocha.github.io/clipboard.js/#usage

回答by Iyappan

function copyTextToClipboard(text) {
    var textArea = document.createElement("textarea");
    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;  
    textArea.style.width = '2em';
    textArea.style.height = '2em'; 
    textArea.style.padding = 0;  
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';   
    textArea.style.background = 'transparent';
    textArea.value = text;
    textArea.id = 'ta';
    document.body.appendChild(textArea);
    //textArea.select();
    var range = document.createRange();
    range.selectNode(textArea);
    textArea.select();
    window.getSelection().addRange(range);
    try {
        var successful = document.execCommand('copy');
    } catch (err) {
         alert('Oops, unable to copy');
    }
    document.body.removeChild(textArea);
    return successful;
}

I Hope this is helpfull

我希望这有帮助

回答by MattOlivos

This is a pretty late response but for those searching in the future and having trouble with implementing the execCommand('copy') event to work for both desktop and mobile devices.

这是一个相当晚的响应,但对于那些将来搜索并且在实现 execCommand('copy') 事件以适用于桌面和移动设备时遇到问题的人。

Cross browser, Mobile friendly and No need to have outside sources or programs

跨浏览器,移动友好,无需外部资源或程序

function CopyString(){
    var StringToCopyElement = document.getElementById('YourId');
    StringToCopyElement.select();

    if(document.execCommand('copy')){
        StringToCopyElement.blur();     
    }else{
        CopyStringMobile();
    }
}

function CopyStringMobile(){
    document.getElementById("YourId").selectionStart = 0;
    document.getElementById("YourId").selectionEnd = 999;
    document.execCommand('copy');

    if (window.getSelection) {
      if (window.getSelection().empty) {  // Chrome
        window.getSelection().empty();
      } else if (window.getSelection().removeAllRanges) {  // Firefox
        window.getSelection().removeAllRanges();
      }
    } else if (document.selection) {  // IE?
      document.selection.empty();
    }
}

Set the CopyString() function to a click event on whatever you're looking to fire the event. This is available to be used on both mobile and desktop operating systems.

将 CopyString() 函数设置为您想要触发事件的任何点击事件。这可用于移动和桌面操作系统。

Explanation

解释

You need to have two different ways of going about selecting the string to copy because as of today, the method for doing so via desktop will not work for mobile devices. I have an if then function to catch if the desktop method worked and if not, to fire the code that will work for a mobile device. This method requires no downloads or links needed. Both methods highlight the text you're looking to copy then fires the copy command to your clipboard, being followed by un-selecting the string you're attempting to copy. You can mix up the code to your liking but this is the way of doing so.

您需要有两种不同的方法来选择要复制的字符串,因为截至今天,通过桌面执行此操作的方法不适用于移动设备。我有一个 if then 函数来捕获桌面方法是否有效,如果无效,则触发适用于移动设备的代码。此方法不需要下载或链接。这两种方法都会突出显示您要复制的文本,然后将复制命令触发到剪贴板,然后取消选择您要复制的字符串。您可以根据自己的喜好混合代码,但这是这样做的方式。