JavaScript 如何检测复制粘贴命令Ctrl+V,Ctrl+C
在本文中,我们将使用JavaScript检测复制粘贴命令Ctrl+V和Ctrl+C。要检测带有“Ctrl”的键的组合,我们使用keydown事件的ctrl属性。它返回一个布尔值来告诉我们键事件触发时是否按下了“ctrl”键。
语法:
event.ctrlKey
返回值:
- true: 当按下“ctrl”键时。
- false: 当未按下“ctrl”键时。
方法: 我们将按照以下方法进行:
- HTML代码: 下面是检测“Ctrl+C”和“Ctrl+V”组合键的文件“index.html”的代码。
- CSS代码: 以下代码演示了上述HTML文件中使用的文件“style.css”。
- Javascript代码: 以下演示了上述HTML文件中使用的文件“script.js”的代码。
示例: 此示例展示了上述方法的使用。
HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<meta http-equiv="X-UA-Compatible"
content="ie-edge">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<textarea cols="30" row="5"
placeholder="Enter Text">
</textarea>
<textarea cols="30" row="5"
placeholder="Paste Text">
</textarea>
</div>
<script src="script.js"></script>
</body>
</html>
CSS代码
.container{
display: flex;
flex-direction: column;
align-items: center;
}
textarea{
margin-top: 20px;
}
Javascript代码
<script>
document.body.addEventListener("keydown", function (ev) {
// function to check the detection
ev = ev || window.event; // Event object 'ev'
var key = ev.which || ev.keyCode; // Detecting keyCode
// Detecting Ctrl
var ctrl = ev.ctrlKey ? ev.ctrlKey : ((key === 17)
? true : false);
// If key pressed is V and if ctrl is true.
if (key == 86 && ctrl) {
// print in console.
console.log("Ctrl+V is pressed.");
}
else if (key == 67 && ctrl) {
// If key pressed is C and if ctrl is true.
// print in console.
console.log("Ctrl+C is pressed.");
}
}, false);
</script>
输出:

极客教程