鍍金池/ 問(wèn)答/HTML/ javascript實(shí)現(xiàn)自動(dòng)復(fù)制內(nèi)容到粘貼板

javascript實(shí)現(xiàn)自動(dòng)復(fù)制內(nèi)容到粘貼板

嘗試了用clipboard.js,但是需要點(diǎn)擊按鈕觸發(fā),自動(dòng)執(zhí)行點(diǎn)擊事件也無(wú)效

<button class="btn" data-clipboard-text="測(cè)試的文本">復(fù)制</button>

......

<script>
  $('.btn').bind("myClick", () => {
    var clipboard = new Clipboard('.btn')
    console.log('success!')
  })
  $('.btn').trigger("myClick")
</script>
   

document.execCommand()也嘗試過(guò), 也是需要按鈕觸發(fā)

回答
編輯回答
無(wú)標(biāo)題

點(diǎn)擊自動(dòng)復(fù)制這塊兒,目前 WebApi 不是很穩(wěn)定,兼容性也不是很好,Chrome ,FF ,Safari 也還好。談?wù)勎乙郧暗膶?shí)現(xiàn)吧。

其實(shí)大的可以分為兩種:
1、如果你的內(nèi)容是在 input 框里面,當(dāng)然也包括 textarea 等,實(shí)現(xiàn)相對(duì)簡(jiǎn)單:

<input id="input" value="hello world"/>
const copyInputValue = (input) => {
  const valueLength = input.value.length;
  input.focus();
  input.setSelectionRange(0, valueLength);
  return document.execCommand('copy');
}
copyInputValue(document.getElementById('input'));

2、另外一種是復(fù)制復(fù)制普通元素內(nèi)文本:具體的代碼我就不寫(xiě)了。
思路就是:通過(guò) window.getSelection() 獲取選取,然后初始化一個(gè) Range ,然后 add進(jìn) selection ,然后執(zhí)行復(fù)制命令。

整體的思路就是:把文本想辦法添加進(jìn)選取,這一步的兼容性做好,然后執(zhí)行 document.execCommand('copy')命令,這一步都一樣。
希望幫到你。

2017年10月30日 18:02