需求:自動(dòng)復(fù)制一段內(nèi)容到剪切板, 讓用戶可以在其他客戶端粘貼(發(fā)小廣告做推廣經(jīng)常要用吧)
window.clipboardData (IE 才有)
是個(gè)很好用的對(duì)象, 但是 只在 IE 才有,
IE 被吐糟了一萬年, 才發(fā)現(xiàn)他有個(gè)不錯(cuò)的地方.
IE 即將退出歷史, 找點(diǎn)其他的吧.
ZeroClipboard (借助Flash)
是一個(gè)不錯(cuò)選擇, 但是他還是借助的 flash 實(shí)現(xiàn)的
本人討厭 Flash, 棄之.
window.prompt
這個(gè)還是算了吧, 一點(diǎn)都不友好. 手機(jī)用戶還需要長(zhǎng)按 再點(diǎn)擊復(fù)制
document.execCommand (今天的豬腳)

簡(jiǎn)介
當(dāng)文檔對(duì)象被轉(zhuǎn)換為設(shè)計(jì)模式的時(shí)候(選中,設(shè)置contentEditable等),文檔對(duì)象提供了一個(gè)execCommand方法,通過給這這個(gè)方法傳遞參數(shù)命令可以操作可編輯區(qū)域的內(nèi)容。這個(gè)方法的命令大多數(shù)是對(duì)文檔選中區(qū)域的操作
(如bold, italics等), 也可以插入一個(gè)元素(如增加一個(gè)a鏈接) 或者修改一個(gè)完整行 (如縮進(jìn)).。當(dāng)元素被設(shè)置了contentEditable,通過執(zhí)行execCommand
方法可以對(duì)當(dāng)前活動(dòng)元素進(jìn)行很多操作。
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand
今天咱們只會(huì)用到 copy .
簡(jiǎn)介里說 當(dāng)文檔對(duì)象被轉(zhuǎn)換為設(shè)計(jì)模式的時(shí)候(選中,設(shè)置contentEditable等),文檔對(duì)象提供了一個(gè)execCommand方法.
但是咱們根本不想出現(xiàn)一個(gè) textarea 好嘛, 否則和window.prompt有啥區(qū)別呢?
最簡(jiǎn)單最有效的方式就是把 textarea 給隱藏起來嘛
const copy = text => {
const textarea = document.createElement("textarea")
textarea.style.position = 'fixed'
textarea.style.top = 0
textarea.style.left = 0
textarea.style.border = 'none'
textarea.style.outline = 'none'
textarea.style.resize = 'none'
textarea.style.background = 'transparent'
textarea.style.color = 'transparent'
textArea.value = text
document.body.appendChild(textarea)
textArea.select()
try {
const msg = document.execCommand('copy') ? 'successful' : 'unsuccessful'
console.log(msg)
} catch (err) {
console.log('unable to copy', err)
}
document.body.removeChild(textarea)
}
demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>copy example</title>
</head>
<body>
<h5>獻(xiàn)給我我可愛的胖子</h5>
<p>
<button class="copy">Copy</button>
</p>
<p>
<textarea cols="50" rows="10" placeholder="這這里粘貼試一下吧!"></textarea>
</p>
<script>
var copyBtn = document.querySelector('.copy')
// 點(diǎn)擊的時(shí)候調(diào)用 copyTextToClipboard() 方法就好了.
copyBtn.onclick = function() {
copyTextToClipboard('隨便復(fù)制點(diǎn)內(nèi)容試試')
}
function copyTextToClipboard(text) {
var textArea = document.createElement("textarea")
textArea.style.position = 'fixed'
textArea.style.top = 0
textArea.style.left = 0
textArea.style.width = '2em'
textArea.style.height = '2em'
textArea.style.padding = 0
textArea.style.border = 'none'
textArea.style.outline = 'none'
textArea.style.boxShadow = 'none'
textArea.style.background = 'transparent'
textArea.value = text
document.body.appendChild(textArea)
textArea.select()
try {
var msg = document.execCommand('copy') ? '成功' : '失敗'
console.log('復(fù)制內(nèi)容 ' + msg)
} catch (err) {
console.log('不能使用這種方法復(fù)制內(nèi)容')
}
document.body.removeChild(textArea)
}
</script>
</body>
</html>