簡體   English   中英

將Javascript復制到剪貼板

[英]Javascript copy to clipboard

我正在嘗試將一些文本復制到網頁中的剪貼板。 我設置了一個文本框,其顯示設置為“無”,並在其中填充了一些文本。 然后,當我單擊我的按鈕時,我嘗試將剪貼板設置為其內容,但我一直為空。

我嘗試了兩種設置剪貼板的方法:設置隱藏字段“ hfCTC”的值並調用ShowCTC2()並設置輸入“ ToCopy”的值並調用ShowCTC(),在兩種情況下,警報均顯示為空。

我不希望按鈕進行回發,所以我在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復制某些內容,則警報會顯示我復制的內容,但是通過代碼設置剪貼板數據似乎失敗。

這篇文章解決了這個問題:

MSIE和addEventListener在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');
      }
    });            

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM