如何使用JavaScript复制到剪贴板?

San*_*ira 3131 javascript clipboard copy-paste

将文本复制到剪贴板的最佳方法是什么?(多浏览器)

我试过了:

function copyToClipboard(text) {
    if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData("Text", text);
    } else {  
        unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
        const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);  
        clipboardHelper.copyString(text);
    }
}
Run Code Online (Sandbox Code Playgroud)

但在Internet Explorer中,它会出现语法错误.在Firefox中,它说unsafeWindow is not defined.

没有闪存的好技巧:Trello如何访问用户的剪贴板?

Dea*_*lor 2029

概观

有三种主要的浏览器API可用于复制到剪贴板:

  1. 异步剪贴板API [navigator.clipboard.writeText]
    • Chrome 66中提供以文字为中心的部分(2018年3月)
    • Access是异步的并且使用JavaScript Promises,可以编写,因此安全用户提示(如果显示)不会中断页面​​中的JavaScript.
    • 可以直接从变量将文本复制到剪贴板.
    • 仅在通过HTTPS提供的页面上受支持.
    • 在Chrome中,活动标签页中的66页可以在没有权限提示的情况下写入剪贴板.
  2. document.execCommand('copy')
    • 大多数浏览器都支持2015年4月〜(请参阅下面的浏览器支持).
    • 访问是同步的,即在页面中停止JavaScript直到完成,包括显示和用户与任何安全提示交互.
    • 从DOM读取文本并将其放在剪贴板上.
    • 在测试期间〜2015年4月,只有Internet Explorer被注意为在写入剪贴板时显示权限提示.
  3. 覆盖复制事件
    • 请参阅覆盖复制事件的剪贴板API文档.
    • 允许您修改任何复制事件在剪贴板上显示的内容,可以包括纯文本以外的其他格式的数据.
    • 这里没有涉及,因为它没有直接回答这个问题.

一般发展说明

在控制台中测试代码时,不要指望与剪贴板相关的命令可以正常工作.通常,页面必须是活动的(Async Clipboard API)或需要用户交互(例如用户单击)以允许(document.execCommand('copy'))访问剪贴板,请参阅下面的更多详细信息.

异步+后备

由于浏览器支持新的Async Clipboard API,您可能希望回退到该document.execCommand('copy')方法以获得良好的浏览器覆盖率.

这是一个简单的例子:

function fallbackCopyTextToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text;
  textArea.style.position="fixed";  //avoid scrolling to bottom
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Fallback: Copying text command was ' + msg);
  } catch (err) {
    console.error('Fallback: Oops, unable to copy', err);
  }

  document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
  if (!navigator.clipboard) {
    fallbackCopyTextToClipboard(text);
    return;
  }
  navigator.clipboard.writeText(text).then(function() {
    console.log('Async: Copying to clipboard was successful!');
  }, function(err) {
    console.error('Async: Could not copy text: ', err);
  });
}

var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
  copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Jane');
});
Run Code Online (Sandbox Code Playgroud)
<div style="display:inline-block; vertical-align:top;">
  <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
  <button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
  <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:

  </textarea>
</div>
Run Code Online (Sandbox Code Playgroud)

请注意,此代码段在Stack Overflow的嵌入式预览中无法正常运行,您可以在此处尝试:https://codepen.io/DeanMarkTaylor/pen/RMRaJX?edit = 1011

异步剪贴板API

请注意,可以通过Chrome 66中的权限API"请求权限"并测试对剪贴板的访问权限.

var text = "Example text to appear on clipboard";
navigator.clipboard.writeText(text).then(function() {
  console.log('Async: Copying to clipboard was successful!');
}, function(err) {
  console.error('Async: Could not copy text: ', err);
});
Run Code Online (Sandbox Code Playgroud)

document.execCommand( '复制')

本文的其余部分将介绍document.execCommand('copy')API 的细微差别和细节.

浏览器支持

JavaScript document.execCommand('copy')支持已经增长,请参阅下面的链接以获取浏览器更新:

简单的例子

var copyTextareaBtn = document.querySelector('.js-textareacopybtn');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.js-copytextarea');
  copyTextarea.focus();
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
Run Code Online (Sandbox Code Playgroud)
<p>
  <button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
  <textarea class="js-copytextarea">Hello I'm some text</textarea>
</p>
Run Code Online (Sandbox Code Playgroud)

复杂示例:复制到剪贴板而不显示输入

如果有一个以上简单例子的伟大工程,textareainput在屏幕上可见的元素.

在某些情况下,您可能希望将文本复制到剪贴板而不显示input/ textarea元素.这是解决此问题的一种方法示例(基本上是插入元素,复制到剪贴板,删除元素):

使用Google Chrome 44,Firefox 42.0a1和Internet Explorer 11.0.8600.17814进行测试.

function copyTextToClipboard(text) {
  var textArea = document.createElement("textarea");

  //
  // *** This styling is an extra step which is likely not required. ***
  //
  // Why is it here? To ensure:
  // 1. the element is able to have focus and selection.
  // 2. if element was to flash render it has minimal visual impact.
  // 3. less flakyness with selection and copying which **might** occur if
  //    the textarea element is not visible.
  //
  // The likelihood is the element won't even render, not even a
  // flash, so some of these are just precautions. However in
  // Internet Explorer the element is visible whilst the popup
  // box asking the user for permission for the web page to
  // copy to the clipboard.
  //

  // 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 = '2em';
  textArea.style.height = '2em';

  // 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';


  textArea.value = text;

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }

  document.body.removeChild(textArea);
}


var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
  copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Jane');
});
Run Code Online (Sandbox Code Playgroud)
<div style="display:inline-block; vertical-align:top;">
  <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
  <button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
  <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:

  </textarea>
</div>
Run Code Online (Sandbox Code Playgroud)

补充说明

仅在用户执行操作时有效

所有document.execCommand('copy')调用必须作为用户操作的直接结果发生,例如单击事件处理程序.这是一种措施,可以防止在用户剪贴板不期望时弄乱用户的剪贴板.

有关详细信息,请参阅此处Google Developers帖子.

剪贴板API

注意完整的剪贴板API草案规范可以在这里找到:https: //w3c.github.io/clipboard-apis/

是否支持?

  • document.queryCommandSupported('copy')true如果命令"由浏览器支持",则应该返回.
  • document.queryCommandEnabled('copy')返回true如果document.execCommand('copy')会成功,如果现在叫.检查以确保从用户启动的线程调用该命令并满足其他要求.

但是,作为浏览器兼容性问题的示例,只有从用户启动的线程调用该命令时,才会true从2015年4月到10月的Google Chrome返回document.queryCommandSupported('copy').

请注意以下兼容性细节

浏览器兼容性细节

虽然通过用户单击调用document.execCommand('copy')包含在try/ catch块中的简单调用将获得最大的兼容性,但以下内容有一些附带条件:

任何调用document.execCommand,document.queryCommandSupporteddocument.queryCommandEnabled应该包含在try/ catchblock中.

不同的浏览器实现和浏览器版本在调用而不是返回时会抛出不同类型的异常false.

不同的浏览器实现仍在不断变化,剪贴板API仍处于草案状态,因此请记住进行测试.

  • 如何直接从变量数据中复制.ie:`var str ="word";`? (37认同)
  • 很抱歉打扰大家,但是“document.execCommand 已经过时了”。请参阅 https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand (27认同)
  • @BubuDaba用JS创建一个虚拟隐藏`<textarea>`,将它附加到`document.body`,将其值设置为变量,并以"copyTextarea"的速度使用它,然后在复制内容后立即将其删除. (10认同)
  • 目前全球 91% 的用户支持剪贴板 API:https://caniuse.com/mdn-api_clipboard_writetext (4认同)
  • Safari或其他任何指标都可以在Safari中实现吗? (3认同)
  • @AyaSalama的关键点在于,除非用户正在采取操作的浏览器出现,否则无法进行"复制"操作.如果元素使用"display:none"设置样式,则用户将无法执行操作,因为他们无法看到它,也无法与之交互. (3认同)
  • 我找到的唯一版本适用于所有浏览器.我发现在Boostrap Modal中使用它时我必须将文本区域附加到模态.如果可以解决问题,我会给+1000!谢谢! (2认同)
  • 这适用于任何人的iPhone Safari吗? (2认同)
  • @tnkh 当然,但替代品(剪贴板 API)尚未完全烘焙和支持。 (2认同)
  • 我刚刚在后备之后添加了焦点重置:`var previousFocusElement = document.activeElement (....所有后备代码...) previousFocusElement.focus();` (2认同)
  • 可以肯定,来到这里的人们正在寻找带有 1 或 2 个限定符的简短片段,而不是战争与和平。 (2认同)

小智 1237

自动复制到剪贴板可能很危险,因此大多数浏览器(IE除外)都非常困难.就个人而言,我使用以下简单的技巧:

function copyToClipboard(text) {
  window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
Run Code Online (Sandbox Code Playgroud)

将向用户显示提示框,其中已选择要复制的文本.现在它足以按Ctrl+ CEnter(关闭框) - 瞧!

现在剪贴板复制操作是SAFE,因为用户手动完成(但是以非常简单的方式).当然,适用于所有浏览器.

<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button>

<script>
  function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
</script>
Run Code Online (Sandbox Code Playgroud)

  • 奇怪的是,这得到457 upvotes而它没有回答问题:在Javascript**复制到剪贴板**! (433认同)
  • 不错的诀窍 - 但请记住它是Mac的Cmd-C (172认同)
  • 仍然没有使用javascript复制到剪贴板^ _ ^ (110认同)
  • 聪明,但这只支持单行. (89认同)
  • 将"提示"功能更改为自定义模式是微不足道的,其诀窍在于使用可编辑的内容字段并预先选择文本,并且通过强制用户执行以下操作不会破坏浏览器UI行动本身.A ++ (61认同)
  • 如果您的文本超过2000个字符,它将被截断,但对于较小的文本样本,它可以很好地工作 (22认同)
  • 但是该对话框中显示的字符数量有限制,因此要复制的数据量有限制. (12认同)
  • @stevenvh因为它解决了这个问题.因为谷歌它并被定向到这个页面的用户不知道它在纯Javascript中实际上是不可能的. (8认同)
  • @RasTheDestroyer - 在2k字符处截断似乎是一个Chrome问题,但无论如何都知道很高兴 (7认同)
  • 这是一个很好而简单的解决方案,但考虑到,Chromium提示窗口**有2000个字符限制**,请查看此主题:http://stackoverflow.com/questions/18088662/text-passed-to-window-提示-得到置换,以 (5认同)
  • 并不完全适合移动设备 (4认同)
  • 工作得很好,但我发现复制和打击进入令人讨厌.我认为一键式解决方案可以提供更好的用户体验. (3认同)
  • @AramKocharyan我在chrome和IE上尝试了新行,两者都为我工作,它没有新行提供它,但是当你将信息粘贴到编辑器中时,新行保留 - IE10和Chrome29无论如何 (2认同)
  • 它是如此简单的方法来做到这一点..谢谢..但是文本没有被选中..有没有办法预选文本? (2认同)
  • 它也不允许您复制HTML. (2认同)
  • @Qix它有579票,因为据我所知,除了你的唯一目标是IE之外,没有办法用纯JavaScript做到这一点.网站使用Flash"始终"执行此操作. (2认同)
  • @ cubuspl42它是最受欢迎的,因为它是最理智的*解决方案. (2认同)
  • 如果我使用平板电脑浏览页面怎么办? (2认同)

Gre*_*owe 269

以下方法适用于Chrome,Firefox,Internet Explorer和Edge以及最新版本的Safari(在2016年10月发布的版本10中添加了复制支持).

  • 创建textarea并将其内容设置为要复制到剪贴板的文本.
  • 将textarea附加到DOM.
  • 选择textarea中的文本.
  • 调用document.execCommand("copy")
  • 从dom中删除textarea.

注意:您将看不到textarea,因为它是在Javascript代码的同一个同步调用中添加和删除的.

如果您自己实现这一点,需要注意的一些事项:

  • 出于安全原因,这只能从事件处理程序(如click)调用(就像打开窗口一样).
  • IE将在第一次更新剪贴板时显示权限对话框.
  • 当textarea聚焦时,IE和Edge将滚动.
  • execCommand()可能会抛出某些情况.
  • 除非您使用textarea,否则可能会吞下新行和制表符.(大多数文章似乎建议使用div)
  • 显示IE对话框时,textarea将可见,您需要隐藏它,或使用IE特定的clipboardData api.
  • 在IE系统中,管理员可以禁用剪贴板API.

以下功能应尽可能干净地处理以下所有问题.如果您发现任何问题或有任何改进建议,请发表评论.

// Copies a string to the clipboard. Must be called from within an
// event handler such as click. May return false if it failed, but
// this is not always possible. Browser support for Chrome 43+,
// Firefox 42+, Safari 10+, Edge and Internet Explorer 10+.
// Internet Explorer: The clipboard feature may be disabled by
// an administrator. By default a prompt is shown the first
// time the clipboard is used (per session).
function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text);

    }
    else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        }
        catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        }
        finally {
            document.body.removeChild(textarea);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/fx6a6n6x/

  • 很好的答案:跨浏览器支持,错误处理+清理.截至今天对queryCommandSupported的新支持,现在可以在Javascript中复制到剪贴板,这应该是可接受的答案,而不是尴尬的'window.prompt("复制到剪贴板:Ctrl + C,输入",文本)'解决方法.IE9中支持window.clipboardData,所以你应该在浏览器支持列表中添加IE9,我想也许IE8和之前也一样,但需要验证. (8认同)
  • @SantiagoCorredoira:2016年,这应该是公认的答案.请考虑重新分配BGT(大绿色勾号). (4认同)
  • @Noitidart我经过测试,它非常适用于firefox 54,chrome 60和边缘浏览器,即使焦点不在html文档中,你所遇到的错误可能是特定于版本FF 55 (3认同)
  • **jQuery UI 用户**:请注意,如果您尝试在模式对话框中使用此函数,您将遇到此方法的问题。我怀疑这是因为 jQuery UI 模式正在管理/操作文档焦点。如果它适合您的用例,一种解决方法是先关闭模式对话框,然后复制文本。或者,简单地使用非模式对话框。我怀疑您也可以修改此函数,以便将文本区域添加到模式而不是正文中。 (3认同)
  • @Noitidart它在这里仍然可以完美工作,专注于开发工具并没有阻止它。顺便说一下,普通的Web应用程序用户将在开发人员工具上做什么 (2认同)

Bre*_*lle 93

如果你想要一个非常简单的解决方案(整合时间不到5分钟)并且开箱即用,那么Clippy是一些更复杂的解决方案的不错选择.

它是由GitHub的联合创始人撰写的.示例Flash嵌入代码如下:

<object
   classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
   width="110"
   height="14"
   id="clippy">
  <param name="movie" value="/flash/clippy.swf"/>
  <param name="allowScriptAccess" value="always"/>
  <param name="quality" value="high"/>
  <param name="scale" value="noscale"/>
  <param NAME="FlashVars" value="text=#{text}"/>
  <param name="bgcolor" value="#{bgcolor}"/>
  <embed
     src="/flash/clippy.swf"
     width="110"
     height="14"
     name="clippy"
     quality="high"
     allowScriptAccess="always"
     type="application/x-shockwave-flash"
     pluginspage="http://www.macromedia.com/go/getflashplayer"
     FlashVars="text=#{text}"
     bgcolor="#{bgcolor}"/>
</object>
Run Code Online (Sandbox Code Playgroud)

请记住#{text}用您需要复制的文本和#{bgcolor}颜色替换.

  • OP想要一个JavaScript解决方案.不闪光. (216认同)
  • 仅供参考,在GitHub上使用Clippy已被ZeroClipboard取代. (64认同)
  • @MT,通过"javascript"有些人的意思是"在浏览器客户端",所以虽然只有JS可能是一个要求,许多有机会得到这个答案的人真的在寻找JS或其他广泛支持的 - 客户端的高科技.Flash并未涉及所有平台,但是对于像剪贴板支持这样的抛光功能,如果它通过弹出对话框改进了UX(当然它确实如此),则值得添加. (21认同)
  • 对于任何感兴趣的人,请在复制repo的URL时检查在GitHub上使用的Clippy. (12认同)
  • 现在依靠Flash意味着让一些百分比的网站访问者无法工作,几乎每个人都在做网络开发是不可接受的. (11认同)
  • 借口,代码的其余部分在哪里?有什么方法可以使用?这是如何整合的?实际下载不包括我在这里提出的问题的例子和问题.非常感谢 (5认同)
  • Clippy是否适用于加载AJAX的内容?试图使链接可以抓取,它最初不在页面中.`zclip`不适合我. (3认同)
  • 并且,我猜这不会在任何没有闪存支持的平台上运行,例如iPad ...... (3认同)

ban*_*ndi 84

从网页读取和修改剪贴板会引起安全和隐私问题.但是,在Internet Explorer中,可以执行此操作.我找到了这个示例代码段:

    <script type="text/javascript">
        function select_all(obj) {
            var text_val=eval(obj);
            text_val.focus();
            text_val.select();
            r = text_val.createTextRange();
            if (!r.execCommand) return; // feature detection
            r.execCommand('copy');
        }
    </script>
    <input value="http://www.sajithmr.com"
     onclick="select_all(this)" name="url" type="text" />
Run Code Online (Sandbox Code Playgroud)

  • 不要使用`if(!document.all)`但是`if(!r.execCommand)`以免任何其他人实现它!Document.all绝对与此无关. (18认同)
  • 使用flash进行简单的复制操作似乎有点矫枉过正,很高兴有一个干净的JS方法来做到这一点.因为我们在公司环境中.IE就好了.谢谢Bandi! (6认同)
  • plz解释什么`execCommand(\\'copy \\');`如果没有复制到IE的剪贴板呢?@mrBorna (4认同)

Mat*_*agg 72

我喜欢这个:

<input onclick="this.select();" type='text' value='copy me' />
Run Code Online (Sandbox Code Playgroud)

如果用户不知道如何在他们的操作系统中复制文本,那么他们很可能也不知道如何粘贴。所以只需自动选择它,剩下的交给用户。


Ric*_*rtz 69

我最近写了一篇关于这个问题的技术博客文章(我在Lucidchart工作,我们最近在剪贴板上进行了大修).

将纯文本复制到剪贴板相对简单,假设您希望在系统复制事件期间(用户按下CtrlC或使用浏览器菜单)执行此操作.

var isIe = (navigator.userAgent.toLowerCase().indexOf("msie") != -1 
           || navigator.userAgent.toLowerCase().indexOf("trident") != -1);

document.addEventListener('copy', function(e) {
    var textToPutOnClipboard = "This is some text";
    if (isIe) {
        window.clipboardData.setData('Text', textToPutOnClipboard);    
    } else {
        e.clipboardData.setData('text/plain', textToPutOnClipboard);
    }
    e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

在系统复制事件期间不将文本放在剪贴板上要困难得多.看起来这些其他答案中的一些提到了通过Flash实现它的方法,这是唯一的跨浏览器方式(据我所知).

除此之外,还有一些基于浏览器的选项.

这是IE中最简单的,您可以随时通过JavaScript访问clipboardData对象:

window.clipboardData
Run Code Online (Sandbox Code Playgroud)

(但是,当您尝试在系统剪切,复制或粘贴事件之外执行此操作时,IE将提示用户授予Web应用程序剪贴板权限.)

在Chrome中,您可以创建Chrome扩展程序,为您提供剪贴板权限(这就是我们为Lucidchart所做的工作).然后,对于安装了扩展程序的用户,您只需要自己触发系统事件:

document.execCommand('copy');
Run Code Online (Sandbox Code Playgroud)

看起来Firefox有一些选项允许用户授予某些站点访问剪贴板的权限,但我没有亲自尝试过这些.

  • 博客文章中没有提到(我希望在不久的将来进行更新),它具有使用execCommand触发剪切和复制的功能。IE10 +,Chrome 43+和Opera29 +支持此功能。在这里阅读。http://updates.html5rocks.com/2015/04/cut-and-copy-commands (2认同)

nik*_*san 57

这是我对那一个的看法..

function copy(text) {
    var input = document.createElement('input');
    input.setAttribute('value', text);
    document.body.appendChild(input);
    input.select();
    var result = document.execCommand('copy');
    document.body.removeChild(input);
    return result;
 }
Run Code Online (Sandbox Code Playgroud)

  • @sof-03 使用 textarea 而不是 input 并添加 `\r\n` 作为换行符 (4认同)
  • 我已经复制了你的答案。它适用于 chrome,这就是我所需要的。 (4认同)

a c*_*der 48

clipboard.js是一个小型非Flash实用程序,允许将文本或HTML数据复制到剪贴板.它非常容易使用,只需包含.js并使用以下内容:

<button id='markup-copy'>Copy Button</button>

<script>
document.getElementById('markup-copy').addEventListener('click', function() {
  clipboard.copy({
    'text/plain': 'Markup text. Paste me into a rich text editor.',
    'text/html': '<i>here</i> is some <b>rich text</b>'
  }).then(
    function(){console.log('success'); },
    function(err){console.log('failure', err);
  });

});
</script>
Run Code Online (Sandbox Code Playgroud)

clipboard.js也在GitHub上.

注意:现在已弃用.迁移到这里.

  • 看起来clipboard.js 已被替换或分叉,但它似乎仍然存在并在 https://www.npmjs.com/package/clipboard 上积极维护 (2认同)

小智 40

JavaScript/TypeScript 中最好、最简单的方法是使用此命令

navigator.clipboard.writeText(textExample);
Run Code Online (Sandbox Code Playgroud)

只需在textExample中传递您想要复制到剪贴板的值

  • 不适用于 IOS (2认同)

Jus*_*tin 35

ZeroClipboard是我发现的最佳跨浏览器解决方案:

<div id="copy" data-clipboard-text="Copy Me!">Click to copy</div>    
<script src="ZeroClipboard.js"></script>
<script>
  var clip = new ZeroClipboard( document.getElementById('copy') );
</script>
Run Code Online (Sandbox Code Playgroud)

如果您需要iOS的非Flash支持,您只需添加一个后备:

clip.on( 'noflash', function ( client, args ) {
    $("#copy").click(function(){            
        var txt = $(this).attr('data-clipboard-text');
        prompt ("Copy link, then click OK.", txt);
    });
});  
Run Code Online (Sandbox Code Playgroud)

http://zeroclipboard.org/

https://github.com/zeroclipboard/ZeroClipboard

  • 与Flash交叉浏览?不适用于iOS和Android 4.4 (25认同)
  • 它有十亿行代码.这绝对是嘲笑.最好不要在项目中包含这样的怪物 (8认同)
  • 有一个简单的版本https://gist.github.com/JamesMGreene/8698897是20K,在74k版本中没有所有的花里胡哨.两者都不是很大.我的猜测是大多数用户都可以使用74k或20k文件下载所需的额外毫秒数,因此复制/粘贴只需一次点击而不是两次. (2认同)

小智 26

从我一直在研究的项目之一,jQuery复制到剪贴板插件,利用Zero Clipboard库.

如果你是一个沉重的jQuery用户,它比原生的Zero Clipboard插件更容易使用.

  • @John你抱怨jQuery在使用Flash的答案中不够JavaScripty;) (19认同)
  • @John:`innerHTML`已经支持跨浏览器很长一段时间了.仅仅因为微软最初提出这个想法并不会让它变得不可靠或专有.它现在也被_finally_添加到官方规范中(在每个主要的浏览器供应商已经添加了对它的支持... _sigh_之后). (17认同)
  • 92kb真的不是那么大,它工作得很快你可以使用`text()`而不是`innerHTML()`如果你喜欢.. (6认同)
  • 在大多数情况下,innerHTML比替代品更好.离开你的高马!它更快,更高效,不需要重新呈现页面. (4认同)
  • @RozzA`92KB`非常棒.直到[LTE](https://en.wikipedia.org/wiki/LTE_%28telecommunication%29)成熟[GPRS​​](https://en.wikipedia.org/wiki/General_Packet_Radio_Service)是[WW移动数据标准] (http://www.track-earth.com/gsm.html),它以"1 KB/s"开头.自己做数学. (4认同)

小智 25

    $("td").click(function (e) {
        var clickedCell = $(e.target).closest("td");
        navigator.clipboard.writeText(clickedCell.text());
        alert(clickedCell.text());
    });
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>First<td>
</tr>
<tr>
<td>Second<td>
</tr>
<tr>
<td>Third<td>
</tr>
<tr>
<td>Fourth<td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我已经阅读了所有答案,截至 2020 年 6 月 1 日,当我终于找到文档时,我一直在努力解决这个问题:

$("td").click(function (e) {
    var clickedCell = $(e.target).closest("td");
    navigator.clipboard.writeText(clickedCell.text());
});
Run Code Online (Sandbox Code Playgroud)

它会将单击的单元格文本写入浏览器剪贴板。

您可以根据需要更改选择器“td”,您可以添加用于调试和/或警报功能的 console.log。

这是文档:https : //developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText


Kho*_*Phi 24

Geesh,不知道为什么没有人指出这个.

在2018年,伙计们,这是你如何去做的:

async copySomething(text?) {
  try {
    const toCopy = text || location.href;
    await navigator.clipboard.writeText(toCopy);
    console.log('Text or Page URL copied');
  }
  catch (err) {
    console.error('Failed to copy: ', err);
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的Angular 6+代码中使用,如下所示:

<button mat-menu-item (click)="copySomething()">
    <span>Copy link</span>
</button>
Run Code Online (Sandbox Code Playgroud)

如果我传入一个字符串,它会复制它.如果没有,请复制页面的URL.

也可以做更多体操到剪贴板的东西.在这里查看更多信息:

https://developers.google.com/web/updates/2018/03/clipboardapi

  • 根据提供的链接,"navigator.clipboard仅支持通过HTTPS提供的页面" (3认同)
  • 请注意,这在 Safari(版本 11.1.2)中不起作用 (2认同)
  • @arjun27 好吧,希望有一天 Apple 能够迎头赶上。尽管此 https://caniuse.com/#feat=clipboard 显示您提到的上述版本得到部分支持。 (2认同)
  • 我得到了两个函数readText,writeText是一个拒绝状态的Promise (2认同)

Jos*_*nce 24

我不愿意对此添加另一个答案,但为了帮助像我这样的菜鸟,而且因为这是我会的最佳谷歌结果。

到 2022 年,要将文本复制到剪贴板,只需一行即可。

navigator.clipboard.writeText(textToCopy);
Run Code Online (Sandbox Code Playgroud)

这将返回一个 Promise,如果复制则解决该 Promise,如果失败则拒绝。

完整的工作函数是这样的:

async function copyTextToClipboard(textToCopy) {
    try {
        await navigator.clipboard.writeText(textToCopy);
        console.log('copied to clipboard')
    } catch (error) {
        console.log('failed to copy to clipboard. error=' + error);
    }
}
Run Code Online (Sandbox Code Playgroud)

警告!如果您在测试时打开了 Chrome 开发工具,它将失败,因为浏览器要启用剪贴板,它需要您将窗口置于焦点中。这是为了防止随机网站在您不想要的情况下更改您的剪贴板。开发工具抢走了这个焦点,因此靠近开发工具,您的测试就会起作用。

如果您想将其他内容(图像等)复制到剪贴板,请查看这些文档。

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API

这在浏览器中得到了很好的支持,您可以使用它。如果您担心 Firefox,请使用权限查询来显示或隐藏按钮(如果浏览器支持)。https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query


Eny*_*yby 22

我找到了以下解决方案:

按键向下处理程序创建"pre"标记.我们将内容设置为复制到此标记,然后对此标记进行选择并在处理程序中返回true.这会调用chrome的标准处理程序并复制所选文本.

如果需要,可以设置恢复先前选择的功能超时.我在Mootools上的实现:

   function EnybyClipboard() {
     this.saveSelection = false;
     this.callback = false;
     this.pastedText = false;

     this.restoreSelection = function() {
       if (this.saveSelection) {
         window.getSelection().removeAllRanges();
         for (var i = 0; i < this.saveSelection.length; i++) {
           window.getSelection().addRange(this.saveSelection[i]);
         }
         this.saveSelection = false;
       }
     };

     this.copyText = function(text) {
       var div = $('special_copy');
       if (!div) {
         div = new Element('pre', {
           'id': 'special_copy',
           'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
         });
         div.injectInside(document.body);
       }
       div.set('text', text);
       if (document.createRange) {
         var rng = document.createRange();
         rng.selectNodeContents(div);
         this.saveSelection = [];
         var selection = window.getSelection();
         for (var i = 0; i < selection.rangeCount; i++) {
           this.saveSelection[i] = selection.getRangeAt(i);
         }
         window.getSelection().removeAllRanges();
         window.getSelection().addRange(rng);
         setTimeout(this.restoreSelection.bind(this), 100);
       } else return alert('Copy not work. :(');
     };

     this.getPastedText = function() {
       if (!this.pastedText) alert('Nothing to paste. :(');
       return this.pastedText;
     };

     this.pasteText = function(callback) {
       var div = $('special_paste');
       if (!div) {
         div = new Element('textarea', {
           'id': 'special_paste',
           'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
         });
         div.injectInside(document.body);
         div.addEvent('keyup', function() {
           if (this.callback) {
             this.pastedText = $('special_paste').get('value');
             this.callback.call(null, this.pastedText);
             this.callback = false;
             this.pastedText = false;
             setTimeout(this.restoreSelection.bind(this), 100);
           }
         }.bind(this));
       }
       div.set('value', '');
       if (document.createRange) {
         var rng = document.createRange();
         rng.selectNodeContents(div);
         this.saveSelection = [];
         var selection = window.getSelection();
         for (var i = 0; i < selection.rangeCount; i++) {
           this.saveSelection[i] = selection.getRangeAt(i);
         }
         window.getSelection().removeAllRanges();
         window.getSelection().addRange(rng);
         div.focus();
         this.callback = callback;
       } else return alert('Fail to paste. :(');
     };
   }
Run Code Online (Sandbox Code Playgroud)

用法:

enyby_clip = new EnybyClipboard(); //init 

enyby_clip.copyText('some_text'); // place this in CTRL+C handler and return true;

enyby_clip.pasteText(function callback(pasted_text) {
        alert(pasted_text);
}); // place this in CTRL+V handler and return true;
Run Code Online (Sandbox Code Playgroud)

在粘贴时,它会创建textarea并以相同的方式工作.

PS可能是这个解决方案可用于创建完全跨浏览器的解决方案,无需闪存.它适用于FF和Chrome.

  • 有人试过吗?听起来像一个漂亮的东西,以防它真的适用于各种浏览器! (2认同)
  • Firefox显示:'SecurityError:操作不安全. (2认同)

Jef*_*ker 22

从最近起__CODE__,__CODE__现在支持document.execCommand('copy')命令.所以我使用Tim Down的旧答案Google Developer的答案组合创建了一些跨浏览器复制到剪贴板功能的功能:

function selectElementContents(el) {
    // Copy textarea, pre, div, etc.
    if (document.body.createTextRange) {
        // IE
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.select();
        textRange.execCommand("Copy");
    } 
    else if (window.getSelection && document.createRange) {
        // Non-Internet Explorer
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy command was ' + msg);
        }
        catch (err) {
            console.log('Oops, unable to copy');
        }
    }
} // end function selectElementContents(el)

function make_copy_button(el) {
    var copy_btn = document.createElement('input');
    copy_btn.type = "button";
    el.parentNode.insertBefore(copy_btn, el.nextSibling);
    copy_btn.onclick = function() {
        selectElementContents(el);
    };

    if (document.queryCommandSupported("copy") || parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42) {
        // Copy works with Internet Explorer 4+, Chrome 42+, Firefox 41+, Opera 29+
        copy_btn.value = "Copy to Clipboard";
    }
    else {
        // Select only for Safari and older Chrome, Firefox and Opera
        copy_btn.value = "Select All (then press Ctrl + C to Copy)";
    }
}
/* Note: document.queryCommandSupported("copy") should return "true" on browsers that support copy
    but there was a bug in Chrome versions 42 to 47 that makes it return "false".  So in those
    versions of Chrome feature detection does not work!
    See https://code.google.com/p/chromium/issues/detail?id=476508
*/

make_copy_button(document.getElementById("markup"));
Run Code Online (Sandbox Code Playgroud)
<pre id="markup">
  Text that can be copied or selected with cross browser support.
</pre>
Run Code Online (Sandbox Code Playgroud)


Pet*_*der 22

我非常成功地使用它(没有 jquery或任何其他框架).

function copyToClp(txt){
    txt = document.createTextNode(txt);
    var m = document;
    var w = window;
    var b = m.body;
    b.appendChild(txt);
    if (b.createTextRange) {
        var d = b.createTextRange();
        d.moveToElementText(txt);
        d.select();
        m.execCommand('copy');
    } 
    else {
        var d = m.createRange();
        var g = w.getSelection;
        d.selectNodeContents(txt);
        g().removeAllRanges();
        g().addRange(d);
        m.execCommand('copy');
        g().removeAllRanges();
    }
    txt.remove();
}
Run Code Online (Sandbox Code Playgroud)

警告

标签转换为空格(至少在chrome中).


Cha*_*ert 21

其他方法将纯文本复制到剪贴板.要复制HTML(即,您可以将结果粘贴到WSIWYG编辑器中),您只能在IE中执行以下操作.这与其他方法根本不同,因为浏览器实际上可视地选择内容.

// create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
    contentEditable = true;
}     
editableDiv.appendChild(someContentElement);          

// select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();  
r.execCommand("Copy");

// deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();   
Run Code Online (Sandbox Code Playgroud)


Dom*_*nic 20

我把我认为最好的一个放在一起.

  • 使用cssText来避免IE中的异常,而不是直接使用样式.
  • 如果有选择,则恢复选择
  • 设置只读,因此键盘不会出现在移动设备上
  • 有一个iOS的解决方法,以便它实际上工作,因为它通常阻止execCommand.

这里是:

const copyToClipboard = (function initClipboardText() {
  const textarea = document.createElement('textarea');

  // Move it off screen.
  textarea.style.cssText = 'position: absolute; left: -99999em';

  // Set to readonly to prevent mobile devices opening a keyboard when
  // text is .select()'ed.
  textarea.setAttribute('readonly', true);

  document.body.appendChild(textarea);

  return function setClipboardText(text) {
    textarea.value = text;

    // Check if there is any content selected previously.
    const selected = document.getSelection().rangeCount > 0 ?
      document.getSelection().getRangeAt(0) : false;

    // iOS Safari blocks programmtic execCommand copying normally, without this hack.
    // https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
    if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
      const editable = textarea.contentEditable;
      textarea.contentEditable = true;
      const range = document.createRange();
      range.selectNodeContents(textarea);
      const sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
      textarea.setSelectionRange(0, 999999);
      textarea.contentEditable = editable;
    }
    else {
      textarea.select();
    }

    try {
      const result = document.execCommand('copy');

      // Restore previous selection.
      if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected);
      }

      return result;
    }
    catch (err) {
      console.error(err);
      return false;
    }
  };
})();
Run Code Online (Sandbox Code Playgroud)


NVR*_*VRM 17

使用最新的Clipboard API和用户交互,这可以立即生效:

copy.addEventListener("pointerdown", () => navigator.clipboard.writeText("Hello World!"))
Run Code Online (Sandbox Code Playgroud)
<button id="copy">Copy Hello World!</button>
Run Code Online (Sandbox Code Playgroud)


HO *_*Pin 16

此代码在 2021 年 5 月进行了测试。在 Chrome、IE、Edge 上工作。下面的“消息”参数是您要复制的字符串值。

<script type="text/javascript">
    function copyToClipboard(message) {
        var textArea = document.createElement("textarea");
        textArea.value = message;
        textArea.style.opacity = "0"; 
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();


        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            alert('Copying text command was ' + msg);
        } catch (err) {
            alert('Unable to copy value , error : ' + err.message);
        }

        document.body.removeChild(textArea);
    }

</script>
Run Code Online (Sandbox Code Playgroud)


mat*_*ins 13

从Flash 10开始,如果操作源自用户与Flash对象的交互,则只能复制到剪贴板.(阅读Adobe Flash 10公告中的相关部分)

解决方案是在Copy按钮上方过度使用flash对象,或者启动副本的任何元素.零剪贴板目前是具有此实现的最佳库.有经验的Flash开发人员可能只想创建自己的库.


小智 13

  <!DOCTYPE html>

  <style>
    #t {
      width: 1px
      height: 1px
      border: none
    }
    #t:focus {
      outline: none
    }
  </style>

  <script>
    function copy(text) {
      var t = document.getElementById('t')
      t.innerHTML = text
      t.select()
      try {
        var successful = document.execCommand('copy')
        var msg = successful ? 'successfully' : 'unsuccessfully'
        console.log('text coppied ' + msg)
      } catch (err) {
        console.log('Unable to copy text')
      }
      t.innerHTML = ''
    }
  </script>

  <textarea id=t></textarea>

  <button onclick="copy('hello world')">
    Click me
  </button>
Run Code Online (Sandbox Code Playgroud)


小智 13

复制文本字段内文本的最佳方法。使用navigator.clipboard.writeText

<input type="text" value="Hello World" id="myId">
<button onclick="myFunction()" >Copy text</button>

<script>
function myFunction() {
  var copyText = document.getElementById("myId");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(copyText.value);
}

</script>
Run Code Online (Sandbox Code Playgroud)


Vas*_*las 12

我找到了以下解决方案:

我将文本隐藏在输入中.因为setSelectionRange不能对隐藏的输入起作用,我暂时将类型更改为文本,复制文本然后再次隐藏它.如果要从元素复制文本,可以将其传递给函数并将其内容保存在目标变量中.

jQuery('#copy').on('click', function () {
    copyToClipboard();
});

function copyToClipboard() {
    var target = jQuery('#hidden_text');

    // Make it visible, so can be focused
    target.attr('type', 'text');
    target.focus();
    // Select all the text
    target[0].setSelectionRange(0, target.val().length);

    // Copy the selection
    var succeed;
    try {
        succeed = document.execCommand("copy");
    }
    catch (e) {
        succeed = false;
    }

    // Hide input again
    target.attr('type', 'hidden');

    return succeed;
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*eat 11

已经有很多答案,但我想添加一个(jQuery).在任何浏览器上都可以像魅力一样工作,也可以在移动设备上工作(即提示有关安全性但是当你接受它时工作正常).

function appCopyToClipBoard(sText)
{
    var oText = false,
        bResult = false;
    try
    {
        oText = document.createElement("textarea");
        $(oText).addClass('clipboardCopier').val(sText).insertAfter('body').focus();
        oText.select();
        document.execCommand("Copy");
        bResult = true;
    }
    catch(e) {
    }

    $(oText).remove();
    return bResult;
}
Run Code Online (Sandbox Code Playgroud)

在你的代码中:

if (!appCopyToClipBoard('Hai there! This is copied to the clipboard.'))
{
    alert('Sorry, copy to clipboard failed.');
}
Run Code Online (Sandbox Code Playgroud)


小智 10

将文本从HTML输入复制到剪贴板

 function myFunction() {
   /* Get the text field */
   var copyText = document.getElementById("myInput");

   /* Select the text field */
   copyText.select();

   /* Copy the text inside the text field */
   document.execCommand("Copy");

   /* Alert the copied text */
   alert("Copied the text: " + copyText.value);
 }
Run Code Online (Sandbox Code Playgroud)
 <!-- The text field -->
 <input type="text" value="Hello Friend" id="myInput">

 <!-- The button used to copy the text -->
<button onclick="myFunction()">Copy text</button>
Run Code Online (Sandbox Code Playgroud)

注意: IE9及更早版本不支持document.execCommand()方法.

来源:W3Schools - 将文本复制到剪贴板


小智 8

在IE以外的浏览器中,您需要使用小型Flash对象来操作剪贴板,例如

  • GvS的建议是使用flash电影吗?这不是同一个想法吗? (6认同)
  • 现在已经过时了……查看 GvS 的建议 (2认同)

小智 8

我在构建自定义网格编辑时遇到了同样的问题(例如Excel)和与Excel的兼容性.我不得不支持选择多个单元格,复制和粘贴.

解决方案:创建一个textarea,您将插入数据供用户复制(对我来说,当用户选择单元格时),设置焦点(例如,当用户按下时Ctrl)并选择整个文本.

因此,当用户点击Ctrl+ C他/她获得他/她选择的复制的单元格时.测试后只需将textarea调整为一个像素(我没有测试它是否将在显示器上工作:无).它适用于所有浏览器,对用户来说是透明的.

粘贴 - 你可以这样做(你的目标不同) - 继续关注textarea并使用onpaste捕捉粘贴事件(在我的项目中,我使用单元格中的textareas进行编辑).

我不能粘贴一个例子(商业项目),但你明白了.


Bar*_*urg 8

这是其他答案之间的一点组合.

var copyToClipboard = function(textToCopy){
    $("body")
        .append($('<textarea name="fname" class="textToCopyInput"/>' )
        .val(textToCopy))
        .find(".textToCopyInput")
        .select();
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        alert('Text copied to clipboard!');
      } catch (err) {
          window.prompt("To copy the text to clipboard: Ctrl+C, Enter", textToCopy);
      }
     $(".textToCopyInput").remove();
}
Run Code Online (Sandbox Code Playgroud)

它使用jQuery,但它当然不需要.如果需要,您可以更改它.我刚才有jQuery供我使用.您还可以添加一些CSS以确保输入不显示.例如:

.textToCopyInput{opacity: 0; position: absolute;}
Run Code Online (Sandbox Code Playgroud)

或者当然你也可以做一些内联样式

.append($('<textarea name="fname" style="opacity: 0;  position: absolute;" class="textToCopyInput"/>' )
Run Code Online (Sandbox Code Playgroud)


小智 8

function copytoclipboard(element) {

    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val('0' + element).select();
    document.execCommand("copy");
    $temp.remove();
}
Run Code Online (Sandbox Code Playgroud)


Oli*_*ock 6

这是@ Chase的答案的扩展,其优点是它可以用于IMAGE和TABLE元素,而不仅仅是IE9上的DIV.

if (document.createRange) {
    // IE9 and modern browsers
    var r = document.createRange();
    r.setStartBefore(to_copy);
    r.setEndAfter(to_copy);
    r.selectNode(to_copy);
    var sel = window.getSelection();
    sel.addRange(r);
    document.execCommand('Copy');  // does nothing on FF
} else {
    // IE 8 and earlier.  This stuff won't work on IE9.
    // (unless forced into a backward compatibility mode,
    // or selecting plain divs, not img or table). 
    var r = document.body.createTextRange();
    r.moveToElementText(to_copy);
    r.select()
    r.execCommand('Copy');
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*cPM 6

我用过clipboard.js

我们可以在npm得到它

npm install clipboard --save
Run Code Online (Sandbox Code Playgroud)

还有凉亭

bower install clipboard --save
Run Code Online (Sandbox Code Playgroud)

用法和示例位于https://zenorocha.github.io/clipboard.js/


Sto*_*net 5

据我所知,这只适用于 Internet Explorer。

另请参阅Dynamic Tools - JavaScript Copy To Clipboard,但它要求用户首先更改配置,即使如此,它似乎也不起作用。


Phi*_*Lho 5

看起来您从Greasemonkey\JavaScript Copy to Clipboard 按钮或此代码段的原始来源中获取了代码...

此代码用于 Greasemonkey,因此是 unsafeWindow。而且我猜 Internet Explorer 中的语法错误来自const特定于 Firefox的关键字(将其替换为var)。

  • @ProfK 在撰写本文时(10 年前...),`const` 仅在 Firefox 中实现并且不是官方的(据我所知)。当然,今天几乎所有的浏览器都支持它。 (2认同)

mrB*_*rna 5

我似乎误解了这个问题,但作为参考,你可以提取一系列DOM(不是剪贴板;与所有现代浏览器兼容),并将它与oncopy和onpaste以及onbeforepaste事件结合起来以获得剪贴板行为.这是实现此目的的代码:

function clipBoard(sCommand) {
  var oRange=contentDocument.createRange();
  oRange.setStart(startNode, startOffset);
  oRange.setEnd(endNode, endOffset);
/* This is where the actual selection happens.
in the above, startNode and endNode are dom nodes defining the beginning 
and end of the "selection" respectively. startOffset and endOffset are 
constants that are defined as follows:

END_TO_END: 2
END_TO_START: 3
NODE_AFTER: 1
NODE_BEFORE: 0
NODE_BEFORE_AND_AFTER: 2
NODE_INSIDE: 3
START_TO_END: 1
START_TO_START: 0

and would be used like oRange.START_TO_END */
      switch(sCommand) {
    case "cut":
          this.oFragment=oRange.extractContents();
      oRange.collapse();
      break;
    case "copy":
      this.oFragment=oRange.cloneContents();
      break;
    case "paste":
      oRange.deleteContents();
      var cloneFragment=this.oFragment.cloneNode(true)
      oRange.insertNode(cloneFragment);
      oRange.collapse();
      break;
  }
}
Run Code Online (Sandbox Code Playgroud)


dva*_*ejo 5

我的错.这仅适用于IE.

这是另一种复制文本的方法:

<p>
    <a onclick="window.clipboardData.setData('text', document.getElementById('Test').innerText);">Copy</a>
</p>
Run Code Online (Sandbox Code Playgroud)

  • 这在当前的Chrome(V31)或FireFox(v25)中不起作用.错误是window.clipboardData未定义.从好的方面来说,它适用于IE9.因此,只要您不关心优秀的浏览器并希望将您的网站锁定为使用不良浏览器,这就是您实现这一目标的方法! (9认同)
  • 我不明白为什么这么多愚蠢的答案。https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_copy_clipboard (2认同)

小智 5

在查找了互联网上的各种方法之后,这是我唯一能够工作的东西.这是一个混乱的话题.世界各地发布了大量解决方案,其中大部分都无效.这对我有用:

注意:此代码仅在作为"onClick"方法的直接同步代码执行时才有效.如果您调用对ajax的异步响应或以任何其他异步方式调用它将无法正常工作

copyToClipboard(text) {
    var copyText = document.createElement("input");
    copyText.type = "text";
    document.body.appendChild(copyText);
    copyText.style = "display: inline; width: 1px;";
    copyText.value = text;
    copyText.focus();
    document.execCommand("SelectAll");
    document.execCommand("Copy");
    copyText.remove();
}
Run Code Online (Sandbox Code Playgroud)

我确实意识到这个代码会在屏幕上显示一个1px宽的组件,显示毫秒,但决定不要担心,这是其他人可以解决的问题,如果真的有问题.


Mau*_*Mau 5

要将选定的文本("要复制的文本")复制到剪贴板,请创建一个Bookmarklet(执行Javsacript的浏览器书签)并执行它(单击它).它将创建一个临时文本区域.

Github的代码:

https://gist.github.com/stefanmaric/2abf96c740191cda3bc7a8b0fc905a7d

(function (text) {
  var node = document.createElement('textarea');
  var selection = document.getSelection();

  node.textContent = text;
  document.body.appendChild(node);

  selection.removeAllRanges();
  node.select();
  document.execCommand('copy');

  selection.removeAllRanges();
  document.body.removeChild(node);
})('Text To Copy');
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

1702317 次

最近记录:

5 年,11 月 前