2017년 6월 1일 목요일

우클릭시 text 복사

우클릭시 '복사' DIV 나타나서 클릭시 우클릭 위의 TEXT를 복사하는 스크립트이다.

원했던 건 우클릭하면 바로 복사 하려고 하였으나,
왜 그런지 document.execCommand("copy"); 가 동작하지 않는다.
그래서 click 이벤트로 발생하기 위해 '복사'div 를 생성하였다.
	function copyToClipboard(value, showNotification, notificationText) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val(value).select();
document.execCommand("copy");
$temp.remove();

if (typeof showNotification === 'undefined') {
showNotification = true;
}
if (typeof notificationText === 'undefined') {
notificationText = "Copied to clipboard";
}

var notificationTag = $("div.copy-notification");
if (showNotification && notificationTag.length == 0) {
notificationTag = $("<div/>", { "class": "copy-notification", text: notificationText });
$("body").append(notificationTag);

notificationTag.fadeIn("slow", function () {
setTimeout(function () {
notificationTag.fadeOut("slow", function () {
notificationTag.remove();
});
}, 10);
});
}
}

var copyData = "";
//$(".context-menu-one").on("contextmenu", function(event) {
$("table").on("contextmenu", function(event) {
event.preventDefault();
$("div.custom-menu").remove();
copyData = $.trim(event.target.textContent);

$("<div class='custom-menu'>복사</div>")
.appendTo("body")
.css({top: event.pageY + "px", left: event.pageX + "px"})
.on("click", function(event) {
event.preventDefault();
copyToClipboard(copyData);
copyData = "";
$("div.custom-menu").remove();
});

$("body").click(function (){
$("div.custom-menu").remove();
});
});


 
/* 우측 클릭 '복사' */
.custom-menu {
z-index:1000;
position: absolute;
background-color:#C0C0C0;
border: 1px solid black;
padding: 2px;
border-radius: 5px;
}

.copy-notification {
color: #ffffff;
background-color: rgba(0,0,0,0.8);
padding: 20px;
border-radius: 30px;
position: fixed;
top: 50%;
left: 50%;
width: 150px;
margin-top: -30px;
margin-left: -85px;
display: none;
text-align:center;
}

참조

댓글 없음:

댓글 쓰기