웹개발/Js & Jquery
[Jquery] 클립보드 복사(copy) 스크립트 (모든 브라우저)
kmhan
2019. 5. 8. 15:52
728x90
반응형
최신 version : 복사할 input박스 필요없음
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
function CopyToClipBoard(textToCopy) {
var successMessage = 'Success! The text was copied to your clipboard';
var errorMessage = 'Oops! Copy to clipboard failed. ';
// navigator clipboard api needs a secure context (https)
if (navigator.clipboard && window.isSecureContext) {
// navigator clipboard api method'
navigator.clipboard.writeText(textToCopy).then(
function () {
/* clipboard successfully set */
console.log(successMessage)
},
function () {
/* clipboard write failed */
console.warn(errorMessage)
}
)
} else
if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
// text area method
var textarea = document.createElement("textarea");
textarea.value = textarea.textContent = textToCopy;
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
var selection = document.getSelection();
var range = document.createRange();
range.selectNode(textarea);
selection.removeAllRanges();
selection.addRange(range);
try {
var successful = document.execCommand('copy'); // Security exception may be thrown by some browsers.
var msg = successful ? console.log(successMessage) : console.warn(errorMessage);
}
catch (ex) {
console.warn(errorMessage, ex);
}
finally {
selection.removeAllRanges();
document.body.removeChild(textarea);
}
}
|
cs |
출처 : https://stackoverflow.com/questions/47931843/javascript-copy-to-clipboard-not-working
2019. 05. 08 version
방법은.. input박스를 안보이게 하나 만들고, 그 안에 value값을 집어넣어서 select되게 한후 복사하는 방법.
주의할 점은 input박스를 hidden처리하면 안된다. display:none도 하면 안되고 opacity를 0으로 하거나 position을 absolute로 해서 가려지게 해야함.
html code |
<a class="clipboardBtn" href="#" onclick="">ns1.sdsns.com</a> <a class="clipboardBtn" href="#" onclick="">211.115.203.112</a> <a class="clipboardBtn" href="#" onclick="">ns2.sdsns.com</a> <a class="clipboardBtn" href="#" onclick="">211.239.157.110</a> <input id="clip_target" type="text" value="" style="position:absolute;top:-9999em;"/> |
jquery |
$('.clipboardBtn').on('click', function(e) { // a의 텍스트값을 가져옴 var text = $(this).html(); //숨겨진 input박스 value값으로 text 변수 넣어줌. $('#clip_target').val(text); //input박스 value를 선택 $('#clip_target').select(); // Use try & catch for unsupported browser try { // The important part (copy selected text) var successful = document.execCommand('copy'); // if(successful) answer.innerHTML = 'Copied!'; // else answer.innerHTML = 'Unable to copy!'; } catch (err) { alert('이 브라우저는 지원하지 않습니다.') } }) |
728x90
반응형