移動端實現複製內容至剪貼板小例子

示例一

HTML部分:

<input type="text" id="text_input" />
<button type="button" id="copy_text">copy</button>

js部分:

var inputElem = document.getElementById('text_input');
var btnElem = document.getElementById('copy_text');
btnElem.addEventListener('click', function() {
  if(!document.execCommand) {
    console.error('copy unsupport');
    return;
  }
  inputElem.select();
  var result = document.execCommand('copy');
  if(result) {
    console.log('copy success');
  } else {
    console.error('copy fail');
  }
});

 


注意事項

  • 檢測當前環境是否支持命令API,這一步不可或缺。
  • 瀏覽器環境不支持命令API,須要合理地提示用戶手動進行復制操做。因此,必定不能設置文本元素 user-select: none;,這樣會使文本不能被選擇。
  • 表單元素必須處於被選中狀態,即調用 inputElement.select() 方法,文本元素沒有 select() 方法。
  • 經測試,不能使用 display: none; 或 visibility: hidden; 來隱藏表單元素。因此,只能將此表單元素,定位至能夠見區域以外。
  • 必須表單元素有用,若是不是表單元素,建議新建input標籤,而後把val賦給input,在進行操做。須要靈活實現

更多方案

  • clipboard.js:不依賴flash的一個插件。實現原理和上面的例子是相似的,使用插件能夠簡化不少開發工做。

 


 

原文見:https://github.com/xiaoyucoding/ask/issues/3

相關文章
相關標籤/搜索