티스토리 뷰

Programming/Web

jquery text copy / image copy

혤혤혤 2017. 1. 24. 16:53
문자 복사
parameter에 카피될 영억의 element가 들어간다.
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}


이미지 복사

출처: http://stackoverflow.com/a/40547470


html

<div class="copyable">
    <img src="images/sherlock.jpg" alt="Copy Image to Clipboard via Javascript."/>
</div>
<div class="copyable">
    <img src="images/stark.jpg" alt="Copy Image to Clipboard via Javascript."/>
</div>

script

<script>
        //Cross-browser function to select content
        function SelectText(element) {
            var doc = document;
            if (doc.body.createTextRange) {
                var range = document.body.createTextRange();
                range.moveToElementText(element);
                range.select();
            } else if (window.getSelection) {
                var selection = window.getSelection();
                var range = document.createRange();
                range.selectNodeContents(element);
                selection.removeAllRanges();
                selection.addRange(range);
            }
        }
        $(".copyable").click(function (e) {
            //Make the container Div contenteditable
            $(this).attr("contenteditable", true);
            //Select the image
            SelectText($(this).get(0));
            //Execute copy Command
            //Note: This will ONLY work directly inside a click listenner
            document.execCommand('copy');
            //Unselect the content
            window.getSelection().removeAllRanges();
            //Make the container Div uneditable again
            $(this).removeAttr("contenteditable");
            //Success!!
            alert("image copied!");
        });
</script>


이미지 붙여넣기가 되는 영역에서는 이미지가 보여지고 

이미지 붙여넣기가 안되는 영역에서는 alt 문장이 보여진다. 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
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
글 보관함