在iphone设备上进行剪贴板复制粘贴工作

时间:2015-09-29 18:41:19

标签: javascript jquery html iphone clipboard

我有网络应用程序,主要用于在移动设备上运行。我有一个按钮,它会将传递的文本复制到设备剪贴板。我正在使用javascript。我的代码在所有移动设备上运行良好,除了iphone和ipad。 谁知道会出现什么问题? 这是我的代码:

CopyToClipboard = function(text, fallback){
    var $t = $('<textarea />');
    $t.val(text).appendTo('body');
    $t.select();
    document.execCommand('copy');
    $t.remove();
    return true;   
};

我也试过这种方式,但没有结果,仍然没有在iphone上工作

function detectIE() {
    var ua = window.navigator.userAgent;

    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
        // IE 12 => return version number
        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }

    // other browser
    return false;
}
function copytext(text) {
    if (detectIE()) {
        window.clipboardData.setData('Text', text);
    }
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    window.clipboardData.setData('Text', copytext);
    textField.remove();
}

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    $(textField).remove();
}

2 个答案:

答案 0 :(得分:19)

试试这个。适合我。

&#13;
&#13;
var copy = function(elementId) {

	var input = document.getElementById(elementId);
	var isiOSDevice = navigator.userAgent.match(/ipad|iphone/i);

	if (isiOSDevice) {
	  
		var editable = input.contentEditable;
		var readOnly = input.readOnly;

		input.contentEditable = true;
		input.readOnly = false;

		var range = document.createRange();
		range.selectNodeContents(input);

		var selection = window.getSelection();
		selection.removeAllRanges();
		selection.addRange(range);

		input.setSelectionRange(0, 999999);
		input.contentEditable = editable;
		input.readOnly = readOnly;

	} else {
	 	input.select();
	}

	document.execCommand('copy');
}
&#13;
<input type="text" id="foo" value="text to copy" />
<button onclick="copy('foo')">Copy text</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

根据CanIUse,iOS上的Safari不支持document.execCommand('copy'),可能是出于安全原因。