Simple copy paste function in JavaScript
How I can make simple copy and paste for text in JavaScript? I would like to achieve that when I select some text in a textarea
, 开发者_开发技巧then I can click on a button to copy it, then I can go to another page right click in another textarea
and choose paste.
Take a look at this library: https://github.com/zeroclipboard/zeroclipboard
You cannot access the clipboard in JavaScript, meaning flash is more or less your only option.
Try this:
function copy() {
if(window.clipboardData) {
window.clipboardData.clearData();
window.clipboardData.setData("Text", document.getElementById('txToCopy').value);
}
}
function paste() {
if(window.clipboardData) {
document.getElementById('txToPaste').value = window.clipboardData.getData("Text");
}
}
<a href="javascript:copy();">Copy</a>
<br />
<input type="text" name="txToCopy" id ="txToCopy"/>
<br /><br />
<a href="javascript:paste();">Paste</a>
<br />
<input type="text" name="txToPaste" id="txToPaste"/>
It's a simple copy and paste function. Its working well in IE.
I hope it helps you.
Assuming you want to fetch user keyboard actions, you probably want to use Hotkeys: https://github.com/jeresig/jquery.hotkeys
I think easiest way (and working in all browsers) is to watch keys pressed by user and if he press CTRL+C, save some data you want to copy into some variable.
I mean something like this:
var myClipboardVariable;
document.onkeyup = function(e){
if ((e.key == 'c') && e.ctrlKey){
// save data (you want to copy) into variable
myClipboardVariable = ....//some data
}
if ((e.key == 'v') && e.ctrlKey){
// paste saved data
.... paste your data from variable myClipboardVariable
}
}
have a look at this MDN article.
If you just want to copy user selected text you can do:
document.execCommand("copy");
if you need to select it previously:
document.getElementById('txToPaste').select();
In my case this code didn't work - it turns out
select()
don't work fordisabled
inputs.you don't need any special permissions if you run it from an
onClick
event listener, if you want another event to trigger the copy you are a bit in trubbles.it works for me on Firefox and chrome, MDN says it won't work for safari but I haven't tested it.
You can use ClipBoard API for this,
//copy
navigator.clipboard.writeText("yuuhhhh");
//paste ,this needs user permission
navigator.clipboard.readText()
Now you can use .then function to do what ever you want.
精彩评论