SW/JavaScript

JavaScript : 복사하여 붙여 넣기 : 예제, 구현

얇은생각 2020. 7. 6. 07:30
반응형

JavaScript : 복사하여 붙여 넣기 : 예제, 구현

 

jQuery와 ZeroClipboard 플래시 확장을 사용하여 복사하여 붙여 넣기 단추를 만드는 방법을 살펴 보았습니다. 이것의 문제는 플래시가 필요하다는 것입니다. 대부분의 웹은 플래시에서 멀어지고 일부 사람들은 브라우저에 플래시를 설치하지 않았으므로 다른 솔루션이 필요합니다.

플래시가 복사 및 붙여 넣기에 사용 된 이유는 주로 브라우저 호환성으로 인한 것입니다. 이제 대부분의 브라우저는 이제 API를 지원하여 웹 API document.execCommand를 사용하여 Javascript를 사용하여 직접 복사하여 붙여 넣을 수 있습니다.

 

 

HTML

먼저 페이지에 HTML을 추가하여 복사 할 컨텐츠를 입력 할 텍스트 상자, 복사 프로세스를 시작하는 클릭 이벤트가있는 버튼 및 컨텐츠를 붙여 넣음으로써 복사를 테스트 할 수있는 텍스트 영역이 필요합니다.

<div>
    <input type="text" id="text-to-copy" placeholder="Enter text" />
    <button id="copy-text">Copy</button>
    <span id="copied-text" style="display: none;">Copied!</span>
</div>

<div>
    <textarea name="paste-area" id="paste-area" cols="30" rows="10" placeholder="Paste it here"></textarea>
</div>

 

 

Copy Text

텍스트를 복사하려면 먼저 클릭 이벤트를 버튼에 추가해야합니다.

document.getElementById('copy-text').addEventListener('click', function(e){
    // Click event
});

 

 

클릭 이벤트 내에서 텍스트 상자 안의 텍스트를 선택해야합니다.

document.getElementById('text-to-copy').select();

 

 

텍스트를 선택한 상태에서 execCommand ( 'copy')를 사용하여 텍스트를 클립 보드에 복사 할 수 있습니다.

copied = document.execCommand('copy');

 

 

이 메소드의 리턴은 텍스트가 복사되었는지 여부에 따라 부울 값이되며, 이 부울 값을 확인하여 메시지를 복사 할 수있는 경우 메시지를 표시 할 수 있습니다.

// Add click event
document.getElementById('copy-text').addEventListener('click', function(e){
  e.preventDefault();

  // Select the text
  document.getElementById('text-to-copy').select();

  var copied;

  try
  {
      // Copy the text
      copied = document.execCommand('copy');
  } 
  catch (ex)
  {
      copied = false;  
  }

  if(copied)
  {
    // Display the copied text message
    document.getElementById('copied-text').style.display = 'block';    
  }

});

 

 

Copy And Paste A Variable

위의 예는 HTML 요소의 내용을 복사하여 붙여 넣는 방법을 보여줍니다. 그러나 내용을 클립 보드에 복사하려는 변수가 있으면 어떻게 될까요? 아래 코드는 변수의 내용을 가져 와서 텍스트 영역 요소를 만들고 텍스트 영역의 값을 설정 한 다음 텍스트 영역의 내용을 클립 보드에 복사하는 방법을 보여줍니다.

copyText (textToCopy) {
  this.copied = false
  
  // Create textarea element
  const textarea = document.createElement('textarea')
  
  // Set the value of the text
  textarea.value = textToCopy
  
  // Make sure we cant change the text of the textarea
  textarea.setAttribute('readonly', '');
  
  // Hide the textarea off the screnn
  textarea.style.position = 'absolute';
  textarea.style.left = '-9999px';
  
  // Add the textarea to the page
  document.body.appendChild(textarea);

  // Copy the textarea
  textarea.select()

  try {
    var successful = document.execCommand('copy');
    this.copied = true
  } catch(err) {
    this.copied = false
  }

  textarea.remove()
}
반응형