【问题标题】:Javascript copy to clipboardJavascript 复制到剪贴板
【发布时间】:2015-08-31 03:59:54
【问题描述】:

我正在尝试将一些文本复制到网页中的剪贴板。我设置了一个文本框,它的显示设置为“无”并用一些文本填充它。然后,当我单击按钮时,我尝试将剪贴板设置为其内容,但我一直为空。

我尝试了两种设置剪贴板的方法:设置隐藏字段“hfCTC”的值并调用 ShowCTC2(),设置输入“ToCopy”的值并调用 ShowCTC(),两种情况下警报都显示为 null。

我不希望按钮做回发,所以我在 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');
}

如果我在 ShowCTC() 中注释掉剪贴板行的清除并执行手动 Ctl-C 复制某些内容,警报会显示我复制的内容,但通过代码设置剪贴板数据似乎失败。

【问题讨论】:

  • 没有these?
  • 简短回答,出于安全原因,您不能这样做。
  • 我在发布问题之前确实搜索了这个,实际上我正在使用的 java 脚本函数已被标记为“答案”,因此可以这样做。我的问题是,是否有人能在代码中找到阻止“window.clipboardData.setData()”设置剪贴板内容的缺陷。
  • 这篇文章解决了这个问题:stackoverflow.com/questions/1695376/….

标签: javascript webforms .net-3.5


【解决方案1】:

这篇文章解决了这个问题:

MSIE and addEventListener Problem in Javascript?.

我将代码更改为以下内容:

<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');
      }
    });            

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2010-11-17
    • 2017-03-02
    • 2010-09-23
    • 1970-01-01
    相关资源
    最近更新 更多