点击鼠标实现复制功能,兼容主流浏览器

1.有一个需求,点击鼠标左键,复制链接,可以将该链接粘贴,实现一个简单的复制粘贴功能

2.代码实现

(1)HTML代码

<!DOCTYPE html>
<html>
	<head>
		<title></title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<script src="https://cdn.bootcss.com/jquery/1.8.3/jquery.js"></script>
	</head>
	<body>
		<p>点击复制后在命令行 CTRL+V看一下</p>
		<input type="text" id="inputText" value="测试文本" />
		<input type="button" id="btn" value="复制" style="margin-right: 20px;"/>
		复制给我<input type="text" />
		<script type="text/javascript">
			var btn = document.getElementById('btn');
			btn.onclick= function() {
				var inputText = document.getElementById('inputText');
				//选择需要复制的对象
				inputText.select(); 
				//进行复制
				document.execCommand('copy');
			};
		</script>
	</body>
</html>

(2)效果

(3)在https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand也有提到

,如果你的浏览器(例如火狐),是很旧的版本(long long ago),可能也会存在兼容问题。

猜你喜欢

转载自blog.csdn.net/hangGe0111/article/details/84633776