How to execute ctrl+c or copy commad using javascript or jquery on button click

孤者浪人 提交于 2019-12-20 01:09:06

问题


Is it possible to execute copy command using click EVENT?

I have some text selected and I want this text to be copied on onClick event, so that I am able to past this text to another page with out using right click or CTRL+C to copy the text.


回答1:


function copyText(){
    var txt = '';
     if (window.getSelection)
        txt = window.getSelection();
    else if (document.getSelection)
        txt = document.getSelection();
    else return;
    document.getElementById("a").value=txt;
    allCopied =document.getElementById("a").createTextRange();
    allCopied.execCommand("RemoveFormat");

   allCopied.execCommand("Copy");
}

but for security reasons most browsers do not allow to modify the clipboard( except Internet explorer).




回答2:


HTML

<form name="myForm">
<span onclick="copyText(this)" >Text1</span>, <span onclick="copyText(this)" >Text2</span>
<br>
<input name="myField"></input>

JavaScript

function copyText(element) {
document.myForm.myField.value = element.innerHTML;
}

Copy to Clip Board Ctrl+C

$("#text1").click(function(){
var holdtext = $("#clipboard").innerText;
Copied = holdtext.createTextRange();
Copied.execCommand("Copy");
});



回答3:


use getselection() to get selected text inside a browser window



来源:https://stackoverflow.com/questions/22530738/how-to-execute-ctrlc-or-copy-commad-using-javascript-or-jquery-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!