如何使用 JavaScript 检测 Ctrl+V、Ctrl+C? [英] How to detect Ctrl+V, Ctrl+C using JavaScript?

查看:35
本文介绍了如何使用 JavaScript 检测 Ctrl+V、Ctrl+C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Javascript检测ctrl+vctrl+c?

How to detect ctrl+v, ctrl+c using Javascript?

我需要限制在我的 textarea 中粘贴,最终用户不应复制和粘贴内容,用户只能在 textarea 中输入文本.

I need to restrict pasting in my textareas, end user should not copy and paste the content, user should only type text in textarea.

如何实现这一目标?

推荐答案

我只是出于兴趣才这样做的.我同意这不是正确的做法,但我认为这应该是操作员的决定......此外,代码可以轻松扩展以添加功能,而不是将其删除(例如更高级的剪贴板,或 Ctrl+s 触发服务器端保存).

I just did this out of interest. I agree it's not the right thing to do, but I think it should be the op's decision... Also the code could easily be extended to add functionality, rather than take it away (like a more advanced clipboard, or Ctrl+s triggering a server-side save).

$(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");
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Ctrl+c Ctrl+v disabled</h3>
<textarea class="no-copy-paste"></textarea>
<br><br>
<h3>Ctrl+c Ctrl+v allowed</h3>
<textarea></textarea>

另外澄清一下,这个脚本需要 jQuery 库.

Also just to clarify, this script requires the jQuery library.

Codepen 演示

由于 Tim Down 的建议(见评论),删除了 3 条冗余行(涉及 e.which)

removed 3 redundant lines (involving e.which) thanks to Tim Down's suggestion (see comments)

添加了对 Mac 的支持(cmd 键而不是 ctrl)

added support for Macs (cmd key instead of ctrl)

这篇关于如何使用 JavaScript 检测 Ctrl+V、Ctrl+C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆