美文网首页
Cocos Creator H5支持剪贴板复制功能

Cocos Creator H5支持剪贴板复制功能

作者: Zszen | 来源:发表于2020-06-10 04:04 被阅读0次

很简单,在任意类内设置函数:

     webCopyString(str:string){
        console.log('复制ing');
    
        var input = str + '';
        const el = document.createElement('textarea');
        el.value = input;
        el.setAttribute('readonly', '');
        // el.style.contain = 'strict';
        el.style.position = 'absolute';
        el.style.left = '-9999px';
        el.style.fontSize = '12pt'; // Prevent zooming on iOS
    
        const selection = getSelection();
        var originalRange = null;
        if (selection.rangeCount > 0) {
            originalRange = selection.getRangeAt(0);
        }
        document.body.appendChild(el);
        el.select();
        el.selectionStart = 0;
        el.selectionEnd = input.length;
    
        var success = false;
        try {
            success = document.execCommand('copy');
        } catch (err) {}
    
        document.body.removeChild(el);
    
        if (originalRange) {
            selection.removeAllRanges();
            selection.addRange(originalRange);
        }
        if(success){
            console.log("复制成功");
        }else{
            console.log("复制失败");
        }
        return success;
    }

调用时直接输入

this.webCopyString(json)

看输出状态是否成功, firefox可以执行

参考:
https://forum.cocos.org/t/creator-h5/58862/5

相关文章

网友评论

      本文标题:Cocos Creator H5支持剪贴板复制功能

      本文链接:https://www.haomeiwen.com/subject/nkoytktx.html