js实现手机端复制功能

105 阅读1分钟
function copyFun () {
				if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) { //区分iPhone设备
					console.log('ios')
					window.getSelection().removeAllRanges(); //这段代码必须放在前面否则无效
					var Url2 = document.getElementById("copy"); //要复制文字的节点
					var range = document.createRange();
					// 选中需要复制的节点
					range.selectNode(Url2);
					// 执行选中元素
					window.getSelection().addRange(range);
					// 执行 copy 操作
					var successful = document.execCommand('copy');
					// 移除选中的元素
					window.getSelection().removeAllRanges();
				} else {
					var text = document.getElementById("copy").innerText;
					const textarea = document.createElement("textarea");
					textarea.style.position = 'fixed';
					textarea.style.top = 0;
					textarea.style.left = 0;
					textarea.style.border = 'none';
					textarea.style.outline = 'none';
					textarea.style.resize = 'none';
					textarea.style.background = 'transparent';
					textarea.style.color = 'transparent';
					textarea.value = text; // 修改文本框的内容
					document.body.appendChild(textarea);
					textarea.select() // 选中文本
					try {
						const msg = document.execCommand('copy') ?
							'successful' : 'unsuccessful';
						console.log("复制成功");
					} catch (err) {
						alert('unable to copy', err);
						console.log("复制失败");
					}
					document.body.removeChild(textarea)
				}
			},