CTRL 键和箭头键允许输入

CTRL key and arrow keys allow in input

本文关键字:许输入 输入 CTRL      更新时间:2023-09-26
<input type="text" id="s" />
jQuery('#s').bind('keyup blur',function()
{ 
    var selectedInput = jQuery(this);
    selectedInput.val( selectedInput.val().replace( /[^a-zA-Z0-9,]/g, '' ) );
});

我想从文本中的任何位置编辑我的文本,所以我希望箭头键()和crtl键使用ctrl + A选择所有文本。

您需要

's添加到正则表达式中以允许空格。不执行左键和右键。

我删除了keyup事件以避免烦人的行为

工作代码片段:

var allowedKeyCodes = [17, 37, 39];
jQuery('#s').bind('blur',function(event){ 
  if($.inArray(event.keyCode, allowedKeyCodes))
    return false;
  var selectedInput = jQuery(this);
  selectedInput.val( selectedInput.val().replace( /[^a-zA-Z0-9,'s]/g, '' ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="s" value="Hello World"/>

只需在代码中添加if条件即可,以下是工作代码。让我知道任何进一步的帮助。

jQuery('#s').bind('keyup blur',function()
 { 
  var selectedInput = jQuery(this);
  if (selectedInput.val().match(/[^a-zA-Z0-9,]/g)) {      
    selectedInput.val( selectedInput.val().replace( /[^a-zA-Z0-9,]/g, '' )   );
 }
});

在这里,是你的答案的jsfiddle链接 http://jsfiddle.net/ug1srcm6/

最简单的方法是限制哪些键将调用函数

jQuery('#s').bind('keyup blur',function(e)
{ 
  var keys=[37, 38, 39, 40];
  // for any special keys you want to ignore
  // add their keycodes to this array
  // left arrow:     37
  // up arrow:   38
  // right arrow:    39
  // down arrow:     40
  
  // then, only call your function if the key press is not one of these keys
  if($.inArray(e.keyCode, keys ) == -1 ){
    var selectedInput = jQuery(this);
    selectedInput.val( selectedInput.val().replace( /[^a-zA-Z0-9,]/g, '' ) );
    
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="s" />

对于 ctrl + 尝试以下操作:

$(document).ready(function()
{
    var ctrlDown = false;
    var ctrlKey = 17, aKey = 86
    $(document).keydown(function(e)
    {
        if (e.keyCode == ctrlKey) 
           ctrlDown = true;
    }).keyup(function(e)
    {
        if (e.keyCode == ctrlKey) 
          ctrlDown = false;
    });
    $(".select-all").keydown(function(e)
    {
        if (ctrlDown && (e.keyCode == aKey)) 
           return false;
    });
});

对于箭头键,请使用以下键代码:

left arrow:     37
up arrow:   38
right arrow:    39
down arrow:     40

对于ctrl + a,我建议您使用这样的机制:https://github.com/adrianmalik/jquery-hotkeys然后,您将能够在示例中执行以下操作:

$('input').hotkey('ctrl+a', function() { /* Here you can do what you want */ });