欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用原生 JavaScript 实现复制功能的方法

最编程 2024-02-15 09:07:06
...
<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')将选中内容加入剪贴板

推荐阅读