移動端實現複製內容至剪貼簿

來源:互聯網
上載者:User

標籤:markdown   console   很多   使用者   文本   ref   func   狀態   api   

需求情境

使用document.execCommand()方法,以下簡稱為“命令API”。

樣本一HTML部分
<input type="text" id="text_input" /><button type="button" id="copy_text">copy</button>
JavaScript部分
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‘);  }});
樣本二

實際開發中,需要複製的內容通常是文本元素中的文本。此時,可以使用一個不在可見地區內的表單元素來變向實現。

HTML部分
<input type="text" id="text_input"  /><p>paragraph</p><button type="button" id="copy_text">copy</button>
CSS部分
#text_input {  position: absolute;  top: -100px;}
JavaScript部分
var inputElem = document.getElementById(‘text_input‘);var btnElem = document.getElementById(‘copy_text‘);var textElem = document.querySelector(‘p‘);btnElem.addEventListener(‘click‘, function() {  if(!document.execCommand) {    console.error(‘當前環境不支援複製功能‘);    return;  }  inputElem.value = textElem.innerText;  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; 來隱藏表單元素。所以,只能將此表單元素,定位至可以見地區之外。
更多方案
  • clipboard.js:不依賴flash的一個外掛程式。實現原理和上面的例子是類似的,使用外掛程式可以簡化很多開發工作。

移動端實現複製內容至剪貼簿

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.