AlexZ33 / lessions

自己练习的各种demo和课程
12 stars 2 forks source link

需浏览器实现的常用功能 #65

Open AlexZ33 opened 5 years ago

AlexZ33 commented 5 years ago

浏览器实现复制粘贴

使用API:document.execCommand

具体参见 https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand

使用示例:

// 普通安卓手机(qq、小米浏览器没有问题)

const input = document.createElement('input')

document.body.appendChild(input);

input.setAttribute('value', '要复制的内容');

input.select()

if (document.execCommand('copy')) {

    document.execCommand('copy')

    console.log('复制成功')

}

// iOS,稍微不一样;没有iOS手机,未测试

const input = document.createElement('input')

document.body.appendChild(input)

input.setAttribute('readonly', 'readonly')

input.setAttribute('value', '要复制的内容')

input.setSelectionRange(0, 9999)

if (document.execCommand('copy')) {

    document.execCommand('copy')

    console.log('复制成功')

}

document.body.removeChild(input)