반응형
Javascript 에서 Clipboard 로 Text 를 복사하는 방법입니다.
우선 jQuery 를 사용하기 때문에 꼭 추가해주세요!!
아래와 같이 작성 후 fn_clipboardcopy 함수를 해당 textbox 등을 넘겨주면 됩니다.
function fn_clipboardcopy(obj) { const textToCopy = $(obj).attr("value"); var msgDiv = '<div id="msgClipboard" style="width:100px; height:30px; line-height:30px; background:#000; text-align:center; position:fixed; left:45%; bottom:50px; display:none;">' + ' <span id="msgClipboardText" style = "color:#fff"> 복사완료</span>' + '</div> '; if ($("#msgClipboard").length < 1) { $("body").append(msgDiv); } copyToClipboard(textToCopy); } function copyToClipboard(textToCopy) { // navigator clipboard api needs a secure context (https) try { if (navigator.clipboard && window.isSecureContext) { // navigator clipboard api method' return navigator.clipboard.writeText(textToCopy); } else { // text area method let textArea = document.createElement("textarea"); textArea.value = textToCopy; // make the textarea out of viewport textArea.style.position = "fixed"; textArea.style.left = "-999999px"; textArea.style.top = "-999999px"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); return new Promise((res, rej) => { // here the magic happens document.execCommand('copy') ? res() : rej(); textArea.remove(); $("#msgClipboardText").text("복사완료"); $("#msgClipboard").show(); $("#msgClipboard").fadeOut(2000); }); } } catch (ex) { $("#msgClipboardText").text("복사실패"); $("#msgClipboard").show(); $("#msgClipboard").fadeOut(2000); } } |
반응형
'IT > Client Script' 카테고리의 다른 글
IE Mode 에서 개발자관리도구 실행하는 방법 (0) | 2023.06.26 |
---|---|
Javascript String 관련 메소드 (0) | 2023.01.18 |
문자를 Date 로 변환 (0) | 2018.06.27 |
JavaScript 정규식 (0) | 2018.01.26 |
JavaScript 금액 표시 정규식 (0) | 2018.01.16 |