Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

jquery - Using execCommand (Javascript) to copy hidden text to clipboard

I'm trying to copy to clipboard without using Flash, I plan to fall back onto Flash with the use of ZeroClipboard if the browser is incompatible with the javascript approach.

I have an onClick listener for the button which looks like:

$(buttonWhereActionWillBeTriggered).click(function(){ 
    var copyDiv = document.getElementById(inputContainingTextToBeCopied);
    copyDiv.focus();
    document.execCommand('SelectAll');
    document.execCommand("Copy", false, null);
}

and an input field as follows:

<input type="text" name="Element To Be Copied" id="inputContainingTextToBeCopied" value="foo"/>

This currently works as expected but the design requires that the field containing the text to be copied is invisible. I have tried both setting type="hidden" and style="display: none" neither of which have succeeded. Both result in the button selecting the whole page and copying the whole content to the user's clipboard.
I'm relatively confident the cause is not browser-based but just in case, I am testing on Chrome (Version 43.0.2357.134 (64-bit)) on Mac OS X 10.10.4.

Is there a way that I can maintain the functionality of when the < input> is visible whilst hiding it? or if not an alternate route I can take?


I'm aware of similar questions, none of which address my problem, either from being too old, not actually using Javascript, or not fitting the particular scenario. Here's a good answer for anyone having similar, less specific issues.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's my solution that doesn't use jQuery:

function setClipboard(value) {
    var tempInput = document.createElement("input");
    tempInput.style = "position: absolute; left: -1000px; top: -1000px";
    tempInput.value = value;
    document.body.appendChild(tempInput);
    tempInput.select();
    document.execCommand("copy");
    document.body.removeChild(tempInput);
}
<!DOCTYPE html>
<html>
<head>
<title>Set Clipboard</title>
</head>
<body>
    <button onclick="setClipboard('foo loves bar')">Set Clipboard</button>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...