본문 바로가기

컴터/Javascript / html

대부분 브라우저 호환되는 클립보드에 텍스트 복사하기 + 출처표기

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


대부분 브라우저에 호환되는 클립보드(clipboard)에 호환되는 텍스트 복사하기


https://jsfiddle.net/jsLfnnvy/12/

https://clipboardjs.com/

http://stackoverflow.com/questions/31593297/using-execcommand-javascript-to-copy-hidden-text-to-clipboard


<!DOCTYPE html>

<html>

<head>

<title>Clipboard Copy</title>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">


<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>


<style>


</style>


<script>


/*

소스1.

<input type="text" class="A" value="test@gmail.com" id="A" />


// jquery 이용시 - 여러개 객체 이벤트 걸때

$(".A").each(function(){

var func=function(){ alert("복사되었습니다."); };

clickedCopyText(this,$(this).text(),func);

});


// 한개의 객체 이벤트 걸때

//clickedCopyText(document.querySelector("#A"), "abc1111", function(){ alert("복사 되였습니다."); });

*/

function clickedCopyText($target,text,endFunc){

if(!endFunc) endFunc=function(){};

if($target.addEventListener){ // ie9 이상


$target.addEventListener("click",function(e){

document.execCommand('copy');

},false);


$target.addEventListener("copy", function(e){

e.preventDefault();

if(e.clipboardData){ // jquery 경우 : e.originalEvent.clipboardData 

e.clipboardData.setData("text/plain", text);

}else if(window.clipboardData){

window.clipboardData.setData("Text", text);

}


endFunc();

},false);


}else{ // ie8 이하

$target.attachEvent("onclick", function(e){

window.clipboardData.setData("Text", text);

endFunc();

});

}

}










/*

소스2. 

jquery 이용시

클릭하는 객체와 복사하는 객체가 같은 객체일때.


<input type="text" class="form-control" value="test@gmail.com" />

clickedCopyTextJq($("input[type='text']"));

*/

function clickedCopyTextJq(target,endFunc){

if(!target) return false;

var $target=$(target);

$target.on({

click:function(e){

    document.execCommand("copy");

}

,copy:function(e){console.log(e)

var $this=$(this),text=$this.val()||$this.text();


e.preventDefault();

if(e.originalEvent.clipboardData){

e.originalEvent.clipboardData.setData("text/plain", text);

} else if(window.clipboardData){

window.clipboardData.setData("Text", text);

}


if(endFunc) endFunc.call(this, e);

else alert("copied!!!");

}

});

}






/*

소스3. *** 강추

http://stackoverflow.com/questions/31593297/using-execcommand-javascript-to-copy-hidden-text-to-clipboard


<textarea class="form-control" rows="5" id="textarea">

<span class="label label-default">Default</span>

<span class="label label-primary">Primary</span>

<span class="label label-success">Success</span>

<span class="label label-info">Info</span>

<span class="label label-warning">Warning</span>

<span class="label label-danger">Danger</span>

</textarea>

<button type="button" id="btn-copy" class="btn-copy" data-dest="#textarea" value="xxx">Copy</button>


clickedCopyTextTarget(".btn-copy");

*/

function clickedCopyTextTarget(target, endFunc) {

if(!target) return false;

var success=true

,range=document.createRange()

,selection=null

,$tmpElem=$('<div>');

$("body").on("click", target, function(e){

var $this=$(this)

,dest=$this.attr("data-dest")||""

,$dest=dest?$(dest):$this

,text=$dest.val()||$dest.text();

if(window.clipboardData){ // For IE

window.clipboardData.setData("Text", text);        

}else{ // etc

$tmpElem.text(text).css({position:"absolute",left:"-1000px",top:"-1000px"}).appendTo("body");

// Select temp element.

range.selectNodeContents($tmpElem.get(0));

selection=window.getSelection();

selection.removeAllRanges();

selection.addRange(range);

try{

 success = document.execCommand("copy", false, null);

}catch(e){

 window.prompt("Copy to clipboard: Ctrl+C, Enter", text);

}

if(success){

 if(!endFunc) alert ("copied!!!");

 else endFunc.call(this, e);

}

}

$tmpElem.remove();

$dest.select();

});// end on

}




/*

소스4. 이벤트 없이 복사만 함


copyExe("copy!!!!");

*/

function copyExe(source,endFunc){

if(window.clipboardData){ // ie

window.clipboardData.setData('Text',source);

if(endFunc) endFunc.call(this, e);

else alert("copied!!!");

}else{ // etc

var $tmpDiv=$('<div style="position:absolute;top:-1000px;left:-1000px;">'+source.replace(/</g,"&lt;").replace(/>/g,"&gt;")+'</div>').appendTo("body")

,range=document.createRange()

,selection=null;


range.selectNodeContents($tmpDiv.get(0));

selection=window.getSelection();

selection.removeAllRanges();

selection.addRange(range);


if(document.execCommand("copy", false, null)){

if(endFunc) endFunc.call(this, e);

else alert("copied!!!");

}else window.prompt("Copy to clipboard: Ctrl+C, Enter", source);


$tmpDiv.remove();

}

}




$(function(){


clickedCopyTextJq($("input[type='text']"));

clickedCopyTextTarget(".btn-copy", function(){ $(this).text("copied!!!"); });

    

});

</script>


</head>

<body>


    <div class="container-fluid">

        <h1>Clipboard Copy <a href="http://nosmoke.tistory.com/2394" target="_blank" class="label label-info">설명</a></h1>

        

        <div class="">

            

            <form>

              <div class="form-group">

                <label for="exampleInputEmail1">이메일 주소</label>

                <input type="text" class="form-control" value="test@gmail.com" />

              </div>

              <div class="form-group">

                <label for="exampleInputPassword1">아이디</label>

                <input type="text" class="form-control" value="id-name" />

              </div>

            </form>

            

            

            <textarea class="form-control" rows="5" id="textarea">

                <span class="label label-default">Default</span>

                <span class="label label-primary">Primary</span>

                <span class="label label-success">Success</span>

                <span class="label label-info">Info</span>

                <span class="label label-warning">Warning</span>

                <span class="label label-danger">Danger</span>

            </textarea>

            <div style="margin:1em 0 0;text-align:center;">

                <button type="button" id="btn-copy" class="btn btn-primary btn-copy" data-dest="#textarea">Copy</button>

            </div>

            

        </div>

        

        

        

    </div>

</body>

</html>