Leon's Blogging

Coding blogging for hackers.

Javascript - Copy Text

| Comments

點一下 button 就能夠複製的功能

1
2
<!-- 一定要是 input 才能夠複製 -->
<input type="hidden" id="copy-text" value="copy text" readonly>
1
2
3
4
5
6
7
8
9
10
11
function copy() {
  // 選擇 dom 
  var copy = document.querySelector('#copy-text');
  // 將 dom 改成 text type
  copy.setAttribute('type', 'text');
  copy.select();
  // 執行複製
  document.execCommand('copy');
  // 再將原本的改成 hidden
  copy.setAttribute('type', 'hidden');
}

Reference:

Comments