js-copy


title: js-copy
date: 2017-07-31 16:06:38
tags: Copy
---html

js 複製功能

原文地址 http://web.jobbole.com/86054/
核心代碼是document.execCommand('copy')複製代碼web

html
<input type="text" id="twitter" value="hello zero i am" />
<button data-copytarget="#twitter">copy</button>
若是是要複製div內的內容則方法是寫一個input框放在頁面外 position:absolute left:-3000000px;定義在頁面的外部(不能夠用hidden 或者display:none)

js
(function() {
  'use strict';
  // click events
  document.body.addEventListener('click', copy, true);
  // event handler
  function copy(e) {
    // find target element
    var
      t = e.target,
      c = t.dataset.copytarget,
      inp = (c ? document.querySelector(c) : null);
    // is element selectable?
    if (inp && inp.select) {
      // select text
      inp.select();
      try {
        if (document.execCommand('copy')) {
          // copy text
          document.execCommand('copy');
          inp.blur();
        } else {
          alert('您的瀏覽器暫不支持複製功能,請手動複製');
        }
      } catch (err) {
        alert('您的瀏覽器暫不支持複製功能,請手動複製');
      }
    }
  }
})();
相關文章
相關標籤/搜索