复制文本到剪贴板 可用H5

话不多说 上代码
在按钮函数里面填CopyToClipboard ("这里填复制文本内容 ");
就实现复制了

function CopyToClipboard (input) {
var textToClipboard = input; //文本到剪贴板

var success = true;
if (window.clipboardData) { // 浏览器
    window.clipboardData.setData ("Text", textToClipboard);
}
else {
    var forExecElement = CreateElementForExecCommand (textToClipboard);
    SelectContent (forExecElement);

    try {
        if (window.netscape && netscape.security) {
            netscape.security.PrivilegeManager.enablePrivilege ("UniversalXPConnect");
        }
        //将选定内容复制到剪贴板
        success = document.execCommand ("copy", false, null);
    }
    catch (e) {
        success = false;
    }
    //移除临时元素
    document.body.removeChild (forExecElement);
}

}

function CreateElementForExecCommand (textToClipboard) {
var forExecElement = document.createElement (“div”);
//在可见区域以外
forExecElement.style.position = “absolute”;
forExecElement.style.left = “-10000px”;
forExecElement.style.top = “-10000px”;
//将必需的文本写入元素并追加到文档中
forExecElement.textContent = textToClipboard;
document.body.appendChild (forExecElement);
//内容编辑模式在火狐的exec命令方法是必要的
forExecElement.contentEditable = true;
return forExecElement;
}

function SelectContent (element) {
//创建一个范围
var rangeToSelect = document.createRange ();
rangeToSelect.selectNodeContents (element);
//选择内容
var selection = window.getSelection ();
selection.removeAllRanges ();
selection.addRange (rangeToSelect);
}

4赞

有空试试看.

cocos creator 里在原生上跑不行啊,请问下怎么弄的啊

你确定原生可以用?native哪来的window和document?

getSelection is not defined
在其他敌方都正常,但是微信小程序上,不能使用

1赞

亲测可用,谢谢分享