H5 复制粘贴 - execCommand

2016-02-16  本文已影响17108人  殷众

需求:自动复制一段内容到剪切板, 让用户可以在其他客户端粘贴(发小广告做推广经常要用吧)

window.clipboardData (IE 才有)

是个很好用的对象, 但是 只在 IE 才有,
IE 被吐糟了一万年, 才发现他有个不错的地方.
IE 即将退出历史, 找点其他的吧.

ZeroClipboard (借助Flash)

是一个不错选择, 但是他还是借助的 flash 实现的
本人讨厌 Flash, 弃之.

window.prompt

这个还是算了吧, 一点都不友好. 手机用户还需要长按 再点击复制

document.execCommand (今天的猪脚)

[兼容性(can I use)](http://caniuse.com/#search=execCommand)

简介
当文档对象被转换为设计模式的时候(选中,设置contentEditable等),文档对象提供了一个execCommand方法,通过给这这个方法传递参数命令可以操作可编辑区域的内容。这个方法的命令大多数是对文档选中区域的操作
(如bold, italics等), 也可以插入一个元素(如增加一个a链接) 或者修改一个完整行 (如缩进).。当元素被设置了contentEditable,通过执行execCommand
方法可以对当前活动元素进行很多操作。
https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand

今天咱们只会用到 copy .

简介里说 当文档对象被转换为设计模式的时候(选中,设置contentEditable等),文档对象提供了一个execCommand方法.

但是咱们根本不想出现一个 textarea 好嘛, 否则和window.prompt有啥区别呢?

最简单最有效的方式就是把 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>献给我我可爱的胖子</h5>
<p>
  <button class="copy">Copy</button>
</p>
<p>
  <textarea cols="50" rows="10" placeholder="这这里粘贴试一下吧!"></textarea>
</p>

<script>

  var copyBtn = document.querySelector('.copy')

  // 点击的时候调用 copyTextToClipboard() 方法就好了.
  copyBtn.onclick = function() {
    copyTextToClipboard('随便复制点内容试试')
  }

  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('复制内容 ' + msg)
    } catch (err) {
      console.log('不能使用这种方法复制内容')
    }

    document.body.removeChild(textArea)
}

</script>

  
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读