原生js粘贴复制【源码】

<html>
<head>
	<meta charset="UTF-8">
	<title>9行代码实现复制内容至剪切板</title>
	<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
  <meta name="renderer" content="webkit">
  <style>
	  body {
	  	padding: 36px;
	  	display: flex;
	  	flex-direction: column;
	  	align-items: center;
	  }
  	.ma-btn {
			border-radius: 4px;
			background: #53a5ec;
			color: #fff;
			font-size: 14px;
			padding: 0.8em 1.6em;
			user-select: none;
			-webkit-appearance: none;
			cursor: pointer;
			text-align: center;
		}
		.ma-btn.extra {
			width: 72px;
			margin-top: 36px;
		}
  </style>
</head>
<body>
	<div class="copy--text copy_text" id="copy">复制到剪贴板的内容</div>
	<div class="ma-btn extra copy_btn">复制</div>
	<script>
		var btn = document.querySelectorAll(".copy_btn")[0],
				copy_text = document.querySelectorAll(".copy_text")[0];
		btn.addEventListener("click",function() {
			copy(copy_text);
		},false); 

		function copy(el) {
			var range = document.createRange();
			var end = el.childNodes.length;
			range.setStart(el,0);
			range.setEnd(el,end);

			var selection = window.getSelection();
			selection.removeAllRanges();
			selection.addRange(range);
			document.execCommand("copy",false,null);
			selection.removeRange(range);
		}
	</script>
</body>
</html>

  

猜你喜欢

转载自www.cnblogs.com/webSong/p/8985858.html