Copy text from a hidden control using JavaScript

2019-08-02 02:20发布

I want to be able to place text in a textarea, and copy it to the clipboard, without displaying the textarea.

To copy the text to the clipboard, I create a button with

onclick = "document.getElementById('txtData').select(); document.execCommand('copy');"

and this works fine.

However, if I try to hide the textarea using either

strStyle = 'display:none;'

strStyle = 'visibility:hidden;'

as per

If I want my textarea to be hidden, how do I do it?

then the copy no longer works. The textarea is hidden in both cases, but I have checked the source HTML and the text I want is still there - it's not like hiding the textarea means its contents aren't actually available.

If a full example is appropriate, here's one I took from http://www.jstips.co/en/javascript/copy-to-clipboard/

<head>
<script type='text/javascript'>
function c2cb () {
document.getElementById("txtInvoice").select();
document.execCommand('copy');
}
</script>
</head>
<body ><form id="frmAdminConsole" name="frmAdminConsole" METHOD="POST">

<textarea id='txtInvoice' cols='80'  style = 'visibility:hidden;'>



        46


JOHN SMITH
GAEL SCOIL NA BFHAL
34 A IVEAGH CRESENT
BELFAST
BT12 6AW



Bubble Ball Football [2017-02-03 09:00]     20  190.00
Nerf Wars [2017-02-05 10:00]    14  190.00
TeamTrek [2017-02-06 12:00]     20  0.00</textarea>

<input type="button" value="Copy!" onclick="c2cb()">

This doesn't work until I remove " style = 'visibility:hidden;'" .

I had what I thought was a D'oh! moment and said "I should use a hidden control", but it doesn't work either.

I would settle for a way to hide the textarea by stealth (make it the same colour as the background or something).

2条回答
乱世女痞
2楼-- · 2019-08-02 02:49

Use style ='display:block; width:0; height:0; opacity: 0;' instead of visibility

<head>
<script type='text/javascript'>
function c2cb () {
document.getElementById("txtInvoice").select();
document.execCommand('copy');
}
</script>
</head>
<body ><form id="frmAdminConsole" name="frmAdminConsole" METHOD="POST">

<textarea id='txtInvoice' cols='80' style='display:block; width:0; height:0; opacity: 0;'>



        46


JOHN SMITH
GAEL SCOIL NA BFHAL
34 A IVEAGH CRESENT
BELFAST
BT12 6AW



Bubble Ball Football [2017-02-03 09:00]     20  190.00
Nerf Wars [2017-02-05 10:00]    14  190.00
TeamTrek [2017-02-06 12:00]     20  0.00</textarea>

<input type="button" value="Copy!" onclick="c2cb()">

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-02 02:49

I don't have enough "reputations" to comment, so this is entered as an answer. I found that Chrome will not copy the content of an element with width: 0 or font-size: 0 (works in FireFox). I have an absolutely positioned element with opacity: 0, height: 0, placed outside the visible area. I can copy that element just fine, but if I add either width: 0 or font-size: 0, Chrome clears the clipboard instead of copying the selection.

查看更多
登录 后发表回答