jQuery – 检测剪切,复制或粘贴事件

jQuery – 检测剪切,复制或粘贴事件

原文: https://howtodoinjava.com/jquery/jquery-detect-cut-copy-or-paste-events/

如果您从事的项目涉及具有客户端输入验证的动态 UI,那么您可以回想起 QA / 测试人员非常普遍的做法,即他们尝试复制大量垃圾文本以创建无效的方案并将它们记录为错误。 我不会评论这类问题的有效性。 在本文的这篇文章中,我将为您提供一个解决方案,如果遇到此问题,您可以使用该解决方案。

请注意,这将始终有效。 无论您使用键盘还是鼠标生成这些事件。

jquery_logo

阅读更多按键事件和击键事件之间的差异检测ENTER

检测剪切复制或粘贴事件

要检测这些事件,您需要以给定的方式为任何输入区域绑定以下事件。

$(document).ready(function() {
	$("#textA").bind({
		copy : function(){
		$('#message').text('copy behaviour detected!');
		},
		paste : function(){
		$('#message').text('paste behaviour detected!');
		},
		cut : function(){
		$('#message').text('cut behaviour detected!');
		}
	});
});	

尝试一下

<html>
	<head>
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
		<style type="text/css">
		span{
			color:green;
			font-weight:bold;
		}
		</style>
	</head>
	<body>
		<h1>Detect Cut, Copy and Paste with jQuery</h1>
		<form action="#">
			<label>Text Box : </label>
			<input id="textA" type="text" size="50" value="Copy, paste or cut any text here" />
		</form>

		<span id="message"></span>

		<script type="text/javascript">
		$(document).ready(function() {
			$("#textA").bind({
				copy : function(){
				$('#message').text('copy behaviour detected!');
				},
				paste : function(){
				$('#message').text('paste behaviour detected!');
				},
				cut : function(){
				$('#message').text('cut behaviour detected!');
				}
			});
		});	
		</script>
	</body>
</html>

祝您学习愉快!