[英]Javascript copy to clipboard
I am trying to copy some text to clipboard in a web page. 我正在尝试将一些文本复制到网页中的剪贴板。 I set a textbox, with its display set to "none" and populate it with some text.
我设置了一个文本框,其显示设置为“无”,并在其中填充了一些文本。 Then when I button is clicked, I try to set the clipboard to its content but I keep getting null.
然后,当我单击我的按钮时,我尝试将剪贴板设置为其内容,但我一直为空。
I tried two ways of setting the clipboard: set the value of a hidden field "hfCTC" and calling ShowCTC2() and setting the value of input "ToCopy" and calling ShowCTC() and the alert shows null in both cases. 我尝试了两种设置剪贴板的方法:设置隐藏字段“ hfCTC”的值并调用ShowCTC2()并设置输入“ ToCopy”的值并调用ShowCTC(),在两种情况下,警报均显示为空。
I don't want the button to do a postback, so I return false in js functions. 我不希望按钮进行回发,所以我在js函数中返回false。
<input type="text" id="ToCopy" style="display:none" />
<asp:HiddenField runat="server" ID="hfCTC" />
<input type="image" id="ibCTC" src="images/CTC.png" onclick="return ShowCTC();" />
function ShowCTC2(){
if (document.all) // IE only
{
if (window.clipboardData && clipboardData.setData)
{
var ctrl = document.getElementById('<%=hfCTC.ClientID %>');
var textToCopy = ctrl.value;
window.clipboardData.setData('Text', ctrl.text);
alert (window.clipboardData.getData ('Text'));
}
}
return false;
}
function ShowCTC(){
if (document.all) // IE only
{
window.clipboardData.clearData ("Text");
select_all();
alert (window.clipboardData.getData ('Text'));
}
return false;
}
function select_all() {
var text_val = document.getElementById('ToCopy');
text_val.focus();
text_val.select();
if (!document.all) return; // IE only
r = text_val.createTextRange();
r.execCommand('copy');
}
If I comment out the clearing of clipboard line in ShowCTC() and do a manual Ctl-C to copy something, the alert shows what I copied but the setting of clipboard data through code seems to fail. 如果我注释掉ShowCTC()中剪贴板行的清除并执行手动Ctl-C复制某些内容,则警报会显示我复制的内容,但是通过代码设置剪贴板数据似乎失败。
This post solved the issue: 这篇文章解决了这个问题:
MSIE and addEventListener Problem in Javascript? MSIE和addEventListener在JavaScript中有问题吗? .
。
I changed the code to the following: 我将代码更改为以下内容:
<input type="image" id="ibCTC" src="images/ibCTC.png" class="js-textareacopybtn" />
<textarea class="js-copytextarea">Hello I'm some text</textarea>
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener){
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent){
el.attachEvent('on'+eventName, eventHandler);
}
}
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');
bindEvent(copyTextareaBtn, 'click',function(event) {
var copyTextarea = document.querySelector('.js-copytextarea');
copyTextarea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Copying text command was ' + msg);
} catch (err) {
alert('Oops, unable to copy');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.