js读写剪切板(ES6方案和兼容方案)

2021/9/14 5:22:18webjs

最新es6方法:

写入:

await navigator.clipboard.writeText('hello world');
await navigator.clipboard.write('<div>hello world</div>');

读取:

const text = await navigator.clipboard.readText();

学习扩展:http://www.ruanyifeng.com/blog/2021/01/clipboard-api.html

兼容方案:

function copyText(text) {
    var textarea = document.createElement("textarea"); //创建input对象
    var currentFocus = document.activeElement; //当前获得焦点的元素
    document.body.appendChild(textarea); //添加元素
    textarea.value = text;
    textarea.focus();
    if (textarea.setSelectionRange) {
        textarea.setSelectionRange(0, textarea.value.length); //获取光标起始位置到结束位置
    } else {
        textarea.select();
    }
    try {
        var flag = document.execCommand("copy"); //执行复制
    } catch (eo) {
        var flag = false;
    }
    document.body.removeChild(textarea); //删除元素
    currentFocus.focus();
    return flag;
}