简体   繁体   English

如何在不使用 Flash 的情况下在 HTML5 中复制到剪贴板?

[英]How can I copy to clipboard in HTML5 without using flash?

I want to use a copy-to-clipboard function in HTML5, but without using flash.我想在 HTML5 中使用复制到剪贴板功能,但不使用 Flash。 Is it possible?是否可以? How?如何?

I tried to implement a copy-to-clipboad function with JavaScript, but it is not working:我试图用 JavaScript 实现复制到剪贴板的功能,但它不起作用:

function Copytoclipboard() {
    var body = document.body,
        range, sel;
    if (document.createRange && window.getSelection) {
        range = document.createRange();
        sel = window.getSelection();
        sel.removeAllRanges();
        try {
            range.selectNodeContents(el);
            sel.addRange(range);
            document.execCommand('Copy');
        } catch (e) {
            range.selectNode(el);
            sel.addRange(range);
            document.execCommand('Copy');
        }
    } else if (body.createTextRange) {
        range = body.createTextRange();
        range.moveToElementText(el);
        range.select();
        range.execCommand('Copy');
    }
}

You can use the HTML5 clipboard api http://www.htmlgoodies.com/html5/other/working-with-clipboard-apis-in-html5-web-apps.html#fbid=eh9tM7GHJWF您可以使用HTML5 clipboard api http://www.htmlgoodies.com/html5/other/working-with-clipboard-apis-in-html5-web-apps.html#fbid=eh9tM7GHJWF

But do note that not all browsers fully support it as of now: http://caniuse.com/#feat=clipboard但请注意,目前并非所有浏览器都完全支持它: http : //caniuse.com/#feat=clipboard

UPDATE: This solution now works in the current version of all major browsers!更新:此解决方案现在适用于所有主要浏览器的当前版本!

 function copyText(text){ function selectElementText(element) { if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var range = document.createRange(); range.selectNode(element); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); } } var element = document.createElement('DIV'); element.textContent = text; document.body.appendChild(element); selectElementText(element); document.execCommand('copy'); element.remove(); } var txt = document.getElementById('txt'); var btn = document.getElementById('btn'); btn.addEventListener('click', function(){ copyText(txt.value); })
 <input id="txt" /> <button id="btn">Copy To Clipboard</button>

Note: Trying to use this solution to copy an empty string or a string that is only whitespace will not work.注意:尝试使用此解决方案复制空字符串或只有空格的字符串是行不通的。

ALTERNATE, SIMPLIFIED SOLUTION替代的简化解决方案

This alternate solution has been tested in Chrome, Safari, and Firefox.此替代解决方案已在 Chrome、Safari 和 Firefox 中进行了测试。

 const txt = document.querySelector('#txt') const btn = document.querySelector('#btn') const copy = (text) => { const textarea = document.createElement('textarea') document.body.appendChild(textarea) textarea.value = text textarea.select() document.execCommand('copy') textarea.remove() } btn.addEventListener('click', (e) => { copy(txt.value) })
 <input id="txt" /> <button id="btn">Copy</button>

Note: This solution will not copy an empty string, but it will copy whitespace.注意:此解决方案不会复制空字符串,但会复制空格。

It's not working because it requires a user interaction such as click.它不起作用,因为它需要用户交互,例如单击。 Otherwise, document.execCommand will not work.否则, document.execCommand将不起作用。 You also might wanna check clipboard.js , it's a super easy library to copy text to clipboard that doesn't require Flash.您可能还想查看clipboard.js ,这是一个非常简单的库,可以将文本复制到不需要 Flash 的剪贴板。

Function for inserting text into the clipboard:将文本插入剪贴板的函数:

function copyStringToClipboard (string) {
    function handler (event){
        event.clipboardData.setData('text/plain', string);
        event.preventDefault();
        document.removeEventListener('copy', handler, true);
    }

    document.addEventListener('copy', handler, true);
    document.execCommand('copy');
}

If you don't care that the contents of the text field will be selected prior to copy, here is two-line solution that works at least in Chrome 56 and Edge, but I bet it works in other browsers as well.如果您不关心在复制之前会选择文本字段的内容,这里有两行解决方案,至少适用于 Chrome 56 和 Edge,但我敢打赌它也适用于其他浏览器。

 function clickListener() { document.getElementById('password').select(); document.execCommand('copy'); } document.getElementById('copy_btn').addEventListener('click', clickListener);
 <input id=password value="test"> <button id=copy_btn>Copy</button>

https://jsfiddle.net/uwd0rm08/ https://jsfiddle.net/uwd0rm08/

You can Use Clipboard.js TO add Copy to clipboard.您可以使用 Clipboard.js 添加复制到剪贴板。 This work without flash take a look on Code Which I use:这项没有闪光灯的工作看看我使用的代码:

 //for copy to clickboard var els = document.querySelectorAll('pre'); for (var i=0; i < els.length; i++) { //for CLIPBOARD var atr = els[i].innerHTML; els[i].setAttribute("data-clipboard-text", atr); //For SELECT var ids = "elementID"+[i] els[i].setAttribute("id", ids); els[i].setAttribute("onclick","selectText(this.id)"); } var btns = document.querySelectorAll('pre'); var clipboard = new ClipboardJS(btns); clipboard.on('success', function(e) { console.log(e); }); clipboard.on('error', function(e) { console.log(e); }); //for select function selectText(id){ var sel, range; var el = document.getElementById(id); //get element id if (window.getSelection && document.createRange) { //Browser compatibility sel = window.getSelection(); if(sel.toString() == ''){ //no text selection window.setTimeout(function(){ range = document.createRange(); //range object range.selectNodeContents(el); //sets Range sel.removeAllRanges(); //remove all ranges from selection sel.addRange(range);//add Range to a Selection. },1); } }else if (document.selection) { //older ie sel = document.selection.createRange(); if(sel.text == ''){ //no text selection range = document.body.createTextRange();//Creates TextRange object range.moveToElementText(el);//sets Range range.select(); //make selection. } } }
 <pre>I Have To Copy it<pre> <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
To Know More About Its Usage visit Source : html5 copy to clipboard 要了解有关其用法的更多信息,请访问来源: html5 复制到剪贴板

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在HTML5中没有flash的情况下将文本复制到剪贴板? - How can I copy text to the clipboard without flash in HTML5? Javascript / HTML复制到剪贴板,不带Flash - Javascript/HTML Copy to clipboard without flash 如何在没有Flash的情况下使用HTML5将实时视频流式传输到Wowza? - How can I stream live video to Wowza using HTML5 without Flash? 我将如何使用 javascript 或 dojo 从链接或按钮实现“将 url 复制到剪贴板”而不使用 Flash - How would I implement 'copy url to clipboard' from a link or button using javascript or dojo without flash 复制到没有Flash的剪贴板 - Copy to clipboard without Flash 如何在不使用 HTML 的情况下将值保存到剪贴板? - How can I save a value to the clipboard without using HTML? Javascript - 如何在不显示文本区域的情况下将文本复制到剪贴板? - Javascript - How can I copy a text to clipboard without displaying a textarea? 如何将HTML标签复制到剪贴板而不进行更改? - How to copy HTML tags to clipboard without changes? 如何在没有 flash 的情况下将 div 的内容复制到剪贴板 - How to copy a div's content to clipboard without flash 如何通过 chrome 的控制台截取 html5 视频的当前帧并将其复制到剪贴板 - How do I take a screenshot of the current frame of an html5 video through chrome's console and copy it to clipboard
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM