JavaScript 中的简单复制粘贴功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5579232/
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
Simple copy paste function in JavaScript
提问by Osama khodrog
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.
如何在 JavaScript 中对文本进行简单的复制和粘贴?我想实现这一点,当我在 a 中选择一些文本时textarea
,然后我可以单击一个按钮来复制它,然后我可以转到另一个页面右键单击另一个页面textarea
并选择粘贴。
回答by Peeter
Take a look at this library: https://github.com/zeroclipboard/zeroclipboard
看看这个库:https: //github.com/zeroclipboard/zeroclipboard
You cannot access the clipboard in JavaScript, meaning flash is more or less your only option.
您无法在 JavaScript 中访问剪贴板,这意味着 Flash 或多或少是您唯一的选择。
回答by Anand Thangappan
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.
这是一个简单的复制和粘贴功能。它在 IE 中运行良好。
I hope it helps you.
我希望它能帮助你。
回答by Enriqe
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.
我认为最简单的方法(并在所有浏览器中工作)是观察用户按下的键,如果他按下 CTRL+C,则保存一些您想要复制到某个变量中的数据。
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
}
}
回答by Gerben Jacobs
Assuming you want to fetch user keyboard actions, you probably want to use Hotkeys: https://github.com/jeresig/jquery.hotkeys
假设您想获取用户键盘操作,您可能想使用热键:https: //github.com/jeresig/jquery.hotkeys