js粘贴板操作

获取粘贴板内容(不兼容IE)

navigator
        .clipboard
        .readText()
        .then((v) => {
            console.log("获取剪贴板成功:", v);
        })
        .catch((v) => {
            console.log("获取剪贴板失败: ", v);
        });

复制内容到粘贴板

不兼容IE:

navigator.clipboard.writeText(1234567)

兼容IE9:

var value = 2345672345

const textarea = document.createElement('textarea')
// textarea 设为 readonly 防止 iOS 下自动唤起键盘
textarea.readOnly = 'readonly'
textarea.style.position = 'absolute'
textarea.style.left = '-9999px'
textarea.value = value
document.body.appendChild(textarea)
textarea.select()
const result = document.execCommand('Copy')
if (result) {
  console.log('复制成功')
}
document.body.removeChild(textarea)

posted @ 2022-03-10 09:56  老邓头3247  阅读(312)  评论(0)    收藏  举报