原生 JS 实现复制功能

2021-10-19 15:43:12 浏览数 (1)

代码语言:javascript复制
<input id="target" type="text" >
	<button onclick="onCopyClick()">复制</button>
	<script type="text/javascript">
		function copyToClipboard (text) {
			if (!document.createRange || !window.getSelection || !document.execCommand) {
				return false;
			}
			const node = document.createElement('span');
			node.innerText = text;
			document.body.appendChild(node);
			const range = document.createRange();
			range.selectNode(node);
			const selection = window.getSelection();
			selection.empty();
			selection.addRange(range);
			document.execCommand('copy');

			selection.empty();
			range.detach();
			document.body.removeChild(node);

			return true;
		}
		function onCopyClick () {
			const target = document.getElementById('target');
			copyToClipboard(target.value);
		}
	</script>

copyToClipboard 方法用来实现复制功能,实现过程:

  1. 创建一个 span
  2. 选中span节点内容
  3. 使用 document.execCommand('copy')将选中内容加入剪贴板

0 人点赞