html5 复制粘贴,H5 复制粘贴 - execCommand

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

window.clipboardData (IE 才有)

是个很好用的对象, 但是 只在 IE 才有,

IE 被吐糟了一万年, 才发现他有个不错的地方.

IE 即将退出历史, 找点其他的吧.

是一个不错选择, 但是他还是借助的 flash 实现的

本人讨厌 Flash, 弃之.

window.prompt

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

document.execCommand (今天的猪脚)

37322bb86a48

[兼容性(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

copy example
献给我我可爱的胖子

Copy

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)

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值