h5文本复制

实现功能:复制指定文字到粘贴板

(注:IOS UIWebView 禁用了 copy、paste、cut命令所以无法执行复制)

 

 实现:(兼容ios 、android 移动设备浏览器,除了IOS UIWebView)

copyText:function (text) {
        var textString = text.toString();
        var input = document.querySelector('#copy-input');

        // input自带的select()方法在苹果端无法进行选择,自己实现
        if (!input) {
          input = document.createElement('input');
          input.id = "copy-input";
          input.readOnly = "readOnly";        // 防止ios聚焦触发键盘事件
          input.style.position = "absolute";
          input.style.left = "-1000px";
          input.style.zIndex = "-1000";
          document.body.appendChild(input)
        }

        input.value = textString;

        var selectText = function(textbox, startIndex, stopIndex) {
            if (textbox.createTextRange) {
              var range = textbox.createTextRange();
              range.collapse(true);
              range.moveStart('character', startIndex);          //起始光标
              range.moveEnd('character', stopIndex - startIndex);//结束光标
              range.select();                                    //不兼容苹果
            } else {
              textbox.setSelectionRange(startIndex, stopIndex);
              textbox.focus();
            }
        }

        selectText(input, 0, textString.length);

        //TODO IOS UIWebView禁用复制命令
        if (document.execCommand('copy')) {
          document.execCommand('copy');
        } else {
          console.log('不兼容');
        }

        input.blur();
    }

注:目前我们游戏是通过app交互来执行复制。绕开IOS UIWebView无法执行复制命令

posted @ 2019-09-24 10:21  小鱼2015  阅读(885)  评论(0编辑  收藏  举报