JS復(fù)制文本方法總結(jié)
1. document.execCommand() 【即將廢棄】
function copy(textValue) { // 動態(tài)創(chuàng)建 textarea 標(biāo)簽 const textarea = document.createElement('textarea') // 將該 textarea 設(shè)為 readonly 防止 iOS 下自動喚起鍵盤,同時將 textarea 移出可視區(qū)域 textarea.readOnly = 'readonly' textarea.style.position = 'absolute' textarea.style.left = '-9999px' // 將要 copy 的值賦給 textarea 標(biāo)簽的 value 屬性 textarea.value = textValue // 將 textarea 插入到 body 中 document.body.appendChild(textarea) // 選中值并復(fù)制 textarea.select() const result = document.execCommand('Copy') if (result) { Vue.prototype.$message({ message: '復(fù)制成功', type: 'success' }); } document.body.removeChild(textarea) }
2. navigator.clipboard.writeText()【微信瀏覽器中無效】
function copy(textValue) { navigator.clipboard.writeText(textValue).then(() => { console.log('復(fù)制成功') }) }
3. Vue項目:安裝clipboard
npm install clipboard --save 然后,引入 clipboard import Clipboard from 'clipboard' 對被點擊的文本或按鈕綁定動態(tài)變量 id="btn" :data-clipboard-text="scope.row.courseNo" <!-- 這里scope.row.courseNo是我要復(fù)制的內(nèi)容 --> <template slot-scope="scope"> <span id="btn" :data-clipboard-text="scope.row.courseNo" @click="copyValue()">{{ scope.row.courseNo }}</span> </template> 方法 copy() { const Message = this.$message var clipBoard = new Clipboard('#btn') clipBoard.on('success', function() { clipBoard.destroy() // 銷毀上一次的復(fù)制內(nèi)容 clipBoard = new Clipboard('#btn') Message.success('復(fù)制成功') }) clipBoard.on('error', function() { Message.info('復(fù)制失敗,請手動復(fù)制') }) }

浙公網(wǎng)安備 33010602011771號