How to Prevent Ctrl V, Ctrl C in JavaScript
Copying and pasting can be convenient for users, but there are situations where you may need to restrict this behavior, such as preventing users from copying sensitive information or manipulating data in a specific field. JavaScript provides a simple solution to detect and prevent Ctrl V and Ctrl C key combinations.
To achieve this, use the following steps:
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>
With this code in place, users will not be able to paste content into the restricted textarea while Ctrl V is pressed. They can still type text or use other keyboard shortcuts as usual.
The above is the detailed content of How to Prevent Ctrl V and Ctrl C in a Specific Textarea Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!