js点击复制到剪切板-移动端兼容ios

1,877 阅读1分钟

没有什么好说的,流程也比较简单,就是创建一个textarea框,然后复制textarea里面的内容,

复制完删除textarea框

直接上代码吧,简单粗暴

 clickCopy(index, e) {
        // 数字没有 .length 不能执行selectText 需要转化成字符串
        const textString = WORD[index].text.toString();//复制的内容
        let input = document.querySelector('#copy-input');
        if (!input) {
            input = document.createElement('textarea');
            input.id = "copy-input";
            input.readOnly = "readOnly";        // 防止ios聚焦触发键盘事件
            input.style.position = "fixed";
            input.style.top = "45%";
            input.style.left = "-1000px";
            input.style.zIndex = "-1000";
            document.body.appendChild(input)
        }
        input.value = textString;
        // ios必须先选中文字且不支持 input.select();
        this.selectText(input, 0, textString.length);
        if (document.execCommand('copy')) {
            document.execCommand('copy');
            this.getShow('复制成功,请前往淘宝/天猫app下单')
        } else {
            this.getShow('该浏览器不支持点击复制到剪贴板')
        }
        input.blur();
        document.body.removeChild(input);
    }
    selectText(textbox, startIndex, stopIndex) {
        if (textbox.createTextRange) {//ie
            const range = textbox.createTextRange();
            range.collapse(true);
            range.moveStart('character', startIndex);//起始光标
            range.moveEnd('character', stopIndex - startIndex);//结束光标
            range.select();//不兼容苹果
        } else {//firefox/chrome
            textbox.setSelectionRange(startIndex, stopIndex);
            textbox.focus();
        }
    }