How to detect Ctrl+V, Ctrl+C using JavaScript?

前端 未结 17 1910
走了就别回头了
走了就别回头了 2020-11-22 13:47

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

I need to restrict pasting in my textareas, end user should not copy and p

相关标签:
17条回答
  • 2020-11-22 14:47

    If you use the ctrlKey property, you don't need to maintain state.

       $(document).keydown(function(event) {
          // Ctrl+C or Cmd+C pressed?
          if ((event.ctrlKey || event.metaKey) && event.keyCode == 67) {
             // Do stuff.
          }
    
          // Ctrl+V or Cmd+V pressed?
          if ((event.ctrlKey || event.metaKey) && event.keyCode == 86) {
             // Do stuff.
          }
    
          // Ctrl+X or Cmd+X pressed?
          if ((event.ctrlKey || event.metaKey) && event.keyCode == 88) {
             // Do stuff.
          } 
        }
    
    0 讨论(0)
  • 2020-11-22 14:47

    i already have your problem and i solved it by the following code .. that accept only numbers

    $('#<%= mobileTextBox.ClientID %>').keydown(function(e) {
                ///// e.which Values
                // 8  : BackSpace , 46 : Delete , 37 : Left , 39 : Rigth , 144: Num Lock 
                if (e.which != 8 && e.which != 46 && e.which != 37 && e.which != 39 && e.which != 144
                    && (e.which < 96 || e.which > 105 )) {
                    return false;
                }
            });
    

    you can detect Ctrl id e.which == 17

    0 讨论(0)
  • 2020-11-22 14:48

    Short solution for preventing user from using context menu, copy and cut in jQuery:

    jQuery(document).bind("cut copy contextmenu",function(e){
        e.preventDefault();
    });
    

    Also disabling text selection in CSS might come handy:

    .noselect {  
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
         user-select: none;
    }
    
    0 讨论(0)
  • 2020-11-22 14:50

    With jquery you can easy detect copy, paste, etc by binding the function:

    $("#textA").bind('copy', function() {
        $('span').text('copy behaviour detected!')
    }); 
    $("#textA").bind('paste', function() {
        $('span').text('paste behaviour detected!')
    }); 
    $("#textA").bind('cut', function() {
        $('span').text('cut behaviour detected!')
    });
    

    More information here: http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/

    0 讨论(0)
  • 2020-11-22 14:50

    You can listen to the keypress event, and halt the default event (entering the text) if it matches the specific keycodes

    0 讨论(0)
提交回复
热议问题