자바스크립트 : span 태그 안에 있는 텍스트를 버튼을 누르면 클립보드로 복사하기

<span class="hm" id="hm">Shoot the moon!</span>

다음의 span 태그 안에 있는 텍스트가 버튼을 누르면 클립보드로 옮겨지게 해봅시다. 요즘은 크롬을 제일 많이 쓰니깐 크롬에서 작동되도록 해봅시다.

일단 버튼을 만들어 보지요.

<button onclick="copy_to_clipboard()">클립보드로 복사</button>

요로코롬.

// copy_to_clipboard() function을 만들어 봅시다.
function copy_to_clipboard() {

var copyText = document.getElementById("hm");
// 이렇게 hm id를 가지고 있는 span을 변수로 지정합니다.

var textArea = document.createElement("textarea");
// textarea를 하나 만들어 줍니다. 복사를 위한 textarea입니다. 차후 제거될 것입니다.

textArea.value = copyText.textContent;
// textarea에 hm span의 text를 복사해서 넣습니다.

textArea.select();
document.execCommand("Copy");
// textarea를 선택해서 복사를 합니다.

textArea.remove();
// 이용가치가 없어진 textarea를 제거합니다.

}

반응형