Front-end
[javascript] HTML요소(div, p, span)의 텍스트를 클립보드로 복사하기 버튼 - Copy Text to Clipboard
셀킴
2023. 2. 22. 16:47
728x90
반응형
자바스크립트를 이용하여 텍스트 복사 버튼을 구현해보자
function copy(id)
{
var r = document.createRange();
r.selectNode(document.getElementById(id));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
위 copy 함수를 onclick 이벤트에 넣어 실행해주면 된다.
(id)에 복사하려는 대상 요소의 id를 넣어주면 된다.
<p id="text1">안녕하세요</p>
<button onclick="copy('text1');return false;">텍스트 복사</button>
"안녕하세요"가 복사될 것이다.
codepen 코드
See the Pen Copy Text to Clipboard by sel (@wimmwell) on CodePen.
728x90
반응형