在非 Microsoft 平台上使用 JavaScript 将文本从 TextArea 复制到剪贴板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3422248/
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-10-25 01:07:48  来源:igfitidea点击:

Copy text from TextArea into clipboard using JavaScript on Non-Microsoft platforms

javascriptclipboardcopy-paste

提问by Vijay Balkawade


I am looking for a javascript function which can copy contents from TextArea into clipboard. On microsoft platform the function works fine, but it fails when I switch to non-microsoft platform such as, FireFox or Safari.
I referred this linkfor the function.


我正在寻找一个可以将 TextArea 中的内容复制到剪贴板的 javascript 函数。在微软平台上,该功能运行良好,但当我切换到非微软平台(如 FireFox 或 Safari)时它会失败。
我参考了这个函数的链接


If anyone knows the solution for this, please help me out.
Thanks in advance.


如果有人知道此问题的解决方案,请帮助我。
提前致谢。

回答by coco puffs

A pure JavaScript solution for copying the contents of a textarea to the clipboard when the user clicks on the textarea:

当用户单击 textarea 时,将 textarea 的内容复制到剪贴板的纯 JavaScript 解决方案:

<script>

function copySelectionText(){
    var copysuccess // var to check whether execCommand successfully executed
    try{
        copysuccess = document.execCommand("copy") // run command to copy selected text to clipboard
    } catch(e){
        copysuccess = false
    }
    return copysuccess
}

function copyfieldvalue(e, id){
    var field = document.getElementById(id)
    field.select()
    var copysuccess = copySelectionText()
}

var bio = document.getElementById('mybio')
bio.addEventListener('mouseup', function(e){
    copyfieldvalue(e, 'mybio')
    var copysuccess = copySelectionText() // copy user selected text to clipboard
}, false)

</script>

Note:If you want to copy only parts of the textarea contents to clipboard, the tutorial Reading and copying selected text to clipboard using JavaScripthas more info on that.

注意:如果您只想将 textarea 内容的一部分复制到剪贴板,教程使用 JavaScript 读取和复制所选文本到剪贴板有更多信息。