好用的js复制代码

均益试过了网上很多的js复制的库或者代码,在浏览器适配上总是不完美。有的不能适配安卓,有的不能适配IOS,有的不能适配微信浏览器。均益好不容易找到一段代码,修改了一下,在电脑端、手机端(安卓和IOS)和微信浏览器均测试通过。现分享如下,如果有哪个浏览器不能适配的,请留言

function copyText(text) {
    let input = document.createElement("input")
    input.value = text
    input.readOnly = "readOnly"
    document.body.appendChild(input)
    input.select() // 选择对象
    input.setSelectionRange(0, text.length) //核心
    document.execCommand("Copy") // 执行浏览器复制命令
    input.remove()
}
Leave a Reply

Your email address will not be published. Required fields are marked *