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

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

问题描述

如何使用Javascript检测 ctrl + v ctrl + c



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



如何做到这一点?

解决方案

我只是出于兴趣。我同意这不是正确的做法,但我认为它应该是操作的决定...此外,代码可以很容易地扩展到增加功能,而不是把它拿走(比如更高级的剪贴板或 Ctrl

$

  $(document)。 +  s 触发服务器端保存。 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 (函数(e){
if(e.keyCode == ctrlKey || e.keyCode == cmdKey)ctrlDown = false;
});

$(。 keydown(function(e){
if(ctrlDown&&(e.keyCode == vKey || e.keyCode == cKey))return false;
});
});

另外,为了澄清,此脚本需要jQuery库。



Codepen演示



<编辑:删除3冗余行(涉及e.which)感谢蒂姆唐的建议(见评论)编辑:增加支持Mac(cmd键而不是ctrl )

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

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

How to achieve this?

解决方案

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;
    });
});

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

Codepen demo

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

EDIT: added support for Macs (cmd key instead of ctrl)

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

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