html中使用原生js实现按钮点击按钮一键复制文本功能

来源:IT星空
访问量:1513
发布日期:2023-08-13

提到html页面中一键复制功能,大家可能想到最多的就是引用clipboard.js来实现。这是一种好的办法,今天在这里介绍一种不借助任何第三方js,用原生js实现的复制功能,话不多说,直接上代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>复制演示</title>
	</head>
	<body>
		<div>
			<button type="button" id="fuzhi">复制演示</button>
		</div>
		<script type="text/javascript">
				document.title='复制演示';
				document.getElementById("fuzhi").addEventListener('touchend', touch, false);
				function touch(event){
				    var node = document.createElement('textarea');
				    node.value = '这里是被复制的文本,生产环境中把这里替换为您需要复制的内容';
				    node.setAttribute('readOnly','readOnly');
				    node.setAttribute('style',"position: fixed; left: 0; top: 0;opacity: 0;");
				    document.getElementsByTagName('body')[0].appendChild(node);
				    setTimeout(function() {
				        node.focus();
				        node.setSelectionRange(0, node.value.length);
				        try{
				            document.execCommand('copy', true);
							alert("复制成功!");
				        } catch(e) {
							alert("复制失败!");
						}
				        node.parentNode.removeChild(node);
				    }, 0);
				}
		</script>
	</body>
</html>

运行效果如下图: