Detecting Ctrl V and Ctrl C in JavaScript
To prevent users from pasting content into a textarea, JavaScript can be utilized to detect and block certain keyboard combinations.
A common approach involves using the keydown and keyup events to monitor for the pressing and releasing of the Ctrl key (ctrlKey or cmdKey for Mac). When Ctrl is detected, subsequent presses of the V (paste) or C (copy) keys are intercepted.
Here's an example code snippet:
<code class="javascript">$(document).ready(function() { var ctrlDown = false, ctrlKey = 17, cmdKey = 91, vKey = 86, cKey = 67; $(document).keydown(function(e) { if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true; }).keyup(function(e) { if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false; }); $(".no-copy-paste").keydown(function(e) { if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)) return false; }); // Document Ctrl + C/V $(document).keydown(function(e) { if (ctrlDown && (e.keyCode == cKey)) console.log("Document catch Ctrl+C"); if (ctrlDown && (e.keyCode == vKey)) console.log("Document catch Ctrl+V"); }); });</code>
In this code, elements with the "no-copy-paste" class have Ctrl V and Ctrl C disabled. The code also logs these key combinations when pressed anywhere in the document.
Implementation
To implement this in a textarea, HTML and CSS can be used:
<code class="html"><h3>Ctrl+c Ctrl+v disabled</h3> <textarea class="no-copy-paste"></textarea> <br><br> <h3>Ctrl+c Ctrl+v allowed</h3> <textarea></textarea></code>
<code class="css">.no-copy-paste { -webkit-user-select: none; /* Chrome/Safari */ -moz-user-select: none; /* Firefox */ -ms-user-select: none; /* IE/Edge */ user-select: none; /* Standard syntax */ }</code>
This approach effectively prevents text from being copied and pasted into protected textareas.
The above is the detailed content of How to Detect and Block Ctrl V and Ctrl C Key Combinations in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!