JS一千问(30):如何将一个字符串复制到剪贴板?

JavaScript将一个字符串复制到剪贴板,主要有三步:

  • 创建一个新的 <textarea> 元素,用目标字符串赋值,并将其添加到 HTML 文档中。
  • 使用 Document.execCommand(‘copy’) 复制到剪贴板。
  • 从 HTML 文档中删除新增的 <textarea> 元素。

实例

    

<!DOCTYPE html>
<html>
<head>
	<title>将一个字符串复制到剪贴板 - 享岚元域</title>
</head>
<body>
<input id='cp' placeholder="请输入">
<div><button onclick="copy()">复制到剪贴板</button><span id='result'></span></div>

<script>
	var doTask = function (value) {
		var temp  = document.createElement('textarea');
		temp.value = value;
		temp.setAttribute('readonly', '');
		temp.style.position = 'absolute';
		temp.style.top = '-99999px';  // 远离视图
		document.body.appendChild(temp);  // 插入文档
		temp.select();
		document.execCommand('copy');
		document.body.removeChild(temp); // 从文档中移除
		show('复制成功!');
	};

	var show = function (value) {
		document.getElementById('result').innerHTML = value;
	}

	var copy = function () {
		var value = document.getElementById('cp').value;
		doTask(value);
	}

</script>
</body>
</html>

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注