在HTML中复制按钮

时间:2017-07-11 16:19:04

标签: javascript html

我正在尝试设置一个复制文本按钮但是我希望它的复制文本不会显示,因此它在页面上占用的空间更少。我基本上只想获得一个复制文本按钮,但文本不会显示在任何地方。我怎么能这样做呢。

<SPAN ID="copytext" STYLE="height:150;width:162;background-color:pink">
Copy Text
</SPAN> 
 <TEXTAREA ID="holdtext" STYLE="display:none;">
</TEXTAREA>
 <BUTTON onClick="ClipBoard();">Copy to Clipboard</BUTTON> 

<SCRIPT LANGUAGE="JavaScript">

 function ClipBoard() 
 {
 holdtext.innerText = copytext.innerText;
 Copied = holdtext.createTextRange();
 Copied.execCommand("Copy");
 }

 </SCRIPT> 

2 个答案:

答案 0 :(得分:0)

您无法复制未显示的元素中的内容。但是,将持有者拉出文档流(因此它不会改变页面上其余元素的布局),然后将其opacity更改为透明将起作用,因为即使{{1是} opacity,该元素仍然被认为是可见的(去图!)。

您还需要小心,因为并非所有浏览器都支持0,如果不支持,则会产生错误,因此需要.execCommand()

try/catch
var input = document.getElementById("data");
var temp = document.getElementById("temp");

// Add copy click event handler to the body so that anytime a copy operation occurs
// our event handler will fire
document.body.addEventListener('click', copy);

// event handler will recieve argument referencing the event itself 
function copy(e) {
  // copy data to placeholder - Don't use .innerText, use .textContent
  temp.value = data.textContent;

  // is element selectable?
  if (temp.select) {

    // select text
    temp.select();
    
    // Not all browsers implement execCommand and, if they don't,
    // an error will be thrown.
    try {
      // copy text
      document.execCommand('copy');
    } catch (err) {
      alert('please press Ctrl/Cmd+C to copy manually');   
    }

  }

}
#temp { 
   position:absolute;
   opacity:0;
}
#copytext {
  height:150;width:162;background-color:pink
}

*此解决方案改编自here

答案 1 :(得分:-1)

以下是我解决问题的方法。

<script>
    var bccList = 'emails here';
    function SetList()
    {


    window.clipboardData.setData('text', bccList);
    }
    </script>

然后,我在onclick="javascript:SetList()

复制它的位置