将所选文字复制到剪贴板(不使用Flash)必须是跨浏览器 [英] Copy selected text to the clipboard WITHOUT using flash - must be cross-browser

查看:249
本文介绍了将所选文字复制到剪贴板(不使用Flash)必须是跨浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个按钮,可以选择 textarea 中的文本,并将其复制到剪贴板。我似乎找不到任何解决方案,在所有浏览器中工作,不使用闪存。

I want to have a button which selects the text in a textarea and copies it to the clipboard. I can't seem to find any solutions which work in all browsers and don't use 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();
}

(焦点不是绝对必要)

推荐答案

execCommand('copy')



它是跨浏览器,但它需要时间,直到每个人都更新他们的浏览器。

execCommand('copy')

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

它的工作原理是使用 document.execCommand('copy' ); 函数。
使用此函数,您将复制选择文本。这不仅适用于textareas,而且与网页上的每个选定文本(例如跨区,p,div等)一起使用。

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 spans, p, div etc.).

可在Internet Explorer 10+,Chrome 43+,Opera 29+和Firefox 41+。

Available in Internet Explorer 10+, Chrome 43+, Opera 29+ and Firefox 41+.

// setup the varriables
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 successful = document.execCommand('copy');

       if(successful) 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>
   

这篇关于将所选文字复制到剪贴板(不使用Flash)必须是跨浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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