javascript复制网页内容 execCommand(´ Copy´ )

本文介绍了一种使用JavaScript实现复制文本到剪贴板的方法,通过创建隐藏的textarea元素并利用document.execCommand('copy')来完成复制操作。此方法简单有效且兼容性良好。

javascript复制网页内容 execCommand(´ Copy´ )

大概就这几种主要方法,前三种要么过于繁琐不太好使要么兼容性不好,今天提供的方法就是最后一种,推荐使用

  • **window.clipboardData (IE 才有)

  • **ZeroClipboard (借助Flash)

  • **window.prompt

  • **document.execCommand


在js里添加这个方法,传入的参数为你将要复制的文字,方法的返回值为是否复制成功
    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()

        var msg = '';
        try {
            msg = document.execCommand('copy') ? '复制成功!' : '复制失败!'
        } catch (err) {
            msg = '不能使用这种方法复制内容'
        }
        document.body.removeChild(textArea)
        return msg;
    }

转自: http://www.jianshu.com/p/37322bb86a48


网上找了几个小时,才写好这个功能。第一次写博客,多多关照,也为方便广大跟我一起学习的码农们,共同进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值