자바스크립트로 클립보드 복사 기능을 구현하는 방법은 아래와 같다.
들어가기에 앞서, select()
함수는 <input>
과 <textarea>
태그에서 상요할 수있는 함수로, 모든 문자열을 선택하게 해준다. execCommand()
함수는 문서의 편집 가능한 영역을 변경할 수 있게 해주는 여러가지 기능을 제공한다.
const onCopy = str => {
const el = document.createElement('textarea');
el.value = str;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
<textarea>
요소의 value값에 복사하고자 하는 string값을 넣어준다.<textarea>
를 현재HTML document에 append해준다.HTMLInputElement.select()
로<textarea>
의 내용을 선택해준다.Document.execCommand('copy')
로<textarea>
의 내용을 클립보드에 복사한다.- 마지막으로 추가한
<textarea>
를 document에서 제거해준다.
위와 같이 코드를 실행할 경우 <textarea>
요소가 document에 추가되고 제거되는 과정에서 잠깐 나타났다가 사라지는 것을 볼 수 있다.
textarea
요소를 화면에서 보이지 않도록 스타일 속성을 추가하여 처리해보자. readonly 속성은 유저가 혹시라도 value값을 수정하거나 하는 행위를 막기 위함이다.
const onCopy = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
'Project Log > I'mticon' 카테고리의 다른 글
프로젝트 후기 (2) | 2019.10.15 |
---|---|
자바스크립트 클립보드 복사기능 - 크로스브라우징 이슈 (0) | 2019.10.08 |
프로젝트 변경 (0) | 2019.10.04 |
이미지 업로드시 미리보여주기 기능 (0) | 2019.09.30 |
개인용 사진첩 만들기 (0) | 2019.09.27 |