본문 바로가기

IT 관련 정리

[JS text 클립보드 복사] div, td 형식에서 내용 클립보드에 복사하는 법

반응형

JS에서  text를 클립보드에 복사하는 방법을 알아보자.

 

JS에서는 클립보드에 내용을 복사하기 위해 아래 함수를 사용한다.

 

document.execCommand("copy");

 

해당 함수를 사용하는 조건은 

 

1. 복사하는 내용이  textarea 혹은 input 태그만 가능

2. 해당 부분이 select() 돼 있어야 함.

 

그런데, 내가 복사해야 할 부분은 <td>태그였고 textarea 혹은 input 태그로 바꿀 수 없었다.

 

아래는 td 태그에서 클립보드 copy 기능 쓰는 법이다.

 

  1. html 코드

 

<tr>
 <th class="thead">행</th>
 <td class="tdata" id="data" ng-click="copyToClipboard('data')">
 data <td>
 </tr>

 

2. js 코드 

 

        $scope.copyToClipboard = function (id) {

            var data = document.getElementById(id).innerText;

            //textarea 임시로 추가 후 제거하는 방법(화면에는 나오지 않음)
            var tmp = document.createElement('textarea');
            tmp.value = data;
            tmp.setAttribute('readonly', '');
            tmp.style.position = 'absolute';
            tmp.style.left = '-9999px';
            document.body.appendChild(tmp);
            tmp.select();
            document.execCommand('copy');
            document.body.removeChild(tmp);
        };

 

출처: https://stackoverflow.com/questions/55947718/js-jquery-copying-contents-of-td-to-clipboard

 

JS/jQuery: Copying Contents of td to clipboard

I'm working on a project where I have a table full of first names, last names, and e-mail addresses. The last td should be a button that allows the user to copy that particular person's e-mail addr...

stackoverflow.com

 

반응형