자바스크립트: 클립보드에 복사하기 기능 만들기
버튼을 누르면 <textarea> 등의 요소 내에 있는 텍스트를 시스템의 클립보드로 복사하는 기능입니다.
먼저 아래 함수를 추가합니다.
1
2
3
4
5
6
7
8
9
function copyToClipboard(text) {
var t = document.createElement("textarea");
document.body.appendChild(t);
t.value = text;
t.select();
document.execCommand('copy');
document.body.removeChild(t);
alert("복사되었습니다.")
}
다음 버튼을 클릭했을 경우 <textarea>의 내용을 가져온 다음 copyToClipboard(text)를 통해 함수를 실행하면 내용이 복사가 됩니다.
1
2
3
4
5
6
var btnCopy = document.getElementById("btn-copy")
btnCopy.addEventListener("click", function (e) {
var text = document.getElementById("main-text").value
copyToClipboard(text)
})
This post is licensed under
CC BY 4.0
by the author.