更改按键

时间:2011-01-05 14:08:53

标签: javascript jquery events keypress keydown

在输入框或contenteditable = true div中,如何修改字母“a”的按键以返回字母“b”的按键?即,每次在div中键入字母“a”时,输出实际上是字母“b”。

我不关心在IE中运行的解决方案 - 只适用于Safari,Chrome和& FF。

在Chrome中,我可以看到按键事件具有属性“charCode”,“keyCode”和“which”,所有这些属性都被分配了按键事件编号。如果我在按键上触发事件,我可以修改这些值,但我无法弄清楚要返回的内容,以便输入的实际键是不同的。例如:

$(window).keypress(function(e){  //$(window) is a jQuery object
    e.charCode = 102;
    e.which = 102;
    e.keyCode = 102;
    console.log(e);
    return e;
});

我还可以看到,除了charCode,和keyCode之外,还有一个“originalEvent”属性,而这个属性又具有这些属性。但是,我无法修改那些(我试过像e.originalEvent.charCode = 102这样的东西)。

6 个答案:

答案 0 :(得分:28)

您无法更改与键事件关联的字符或键,也无法完全模拟键事件。但是,您可以自己处理按键并在当前插入点/插入符号处手动插入所需的字符。我已经在Stack Overflow上的许多地方提供了代码来执行此操作。对于contenteditable元素:

这是一个jsFiddle示例:http://www.jsfiddle.net/Ukkmu/4/

输入:

跨浏览器jsFiddle示例:http://www.jsfiddle.net/EXH2k/6/

IE> = 9和非IE jsFiddle示例:http://www.jsfiddle.net/EXH2k/7/

答案 1 :(得分:1)

您可以对<input><textarea>执行的操作只是确保该值中没有任何“a”字符:

$('input.whatever').keypress(function() {
  var inp = this;
  setTimeout(function() {
    inp.value = inp.value.replace(/a/g, 'b');
  }, 0);
});

这种方法可能无法处理你可以用真正换掉“按下”字符的东西所带来的所有可能的技巧,但我不知道实际做到这一点的任何方法。

编辑 - 哦,我在超时处理程序中发生“fixup”的情况下输入的原因是它确保浏览器有机会处理本机行为“按键”事件。当超时处理程序代码运行时,我们确定该元素的值将被更新。我意识到,这个代码有一丝货物崇拜。

答案 2 :(得分:1)

我的解决方案示例(将input[type=text]字符','更改为'.'):

element.addEventListener('keydown', function (event) {
if(event.key === ','){
  setTimeout(function() {
    event.target.value += '.';
  }, 4);
  event.preventDefault();
};

答案 3 :(得分:0)

我不确定这是否“容易”可行,具体如下:

$(window).keypress(function(e) { 
    //Captures 'a' or 'A'
    if(e.which == 97 || e.which == 65)
    {
        //Simulate a keypress in a specific field  
    }
});

我知道jQuery有一个模拟插件来模拟按键事件等jQuery Simulate。可能值得研究 - 也可能是某种类型的jQuery Trigger()事件。

答案 4 :(得分:0)

这里是不使用任何库的示例

const input = document.querySelector('input')

// this is the order of events into an input
input.addEventListener('focus', onFocus)
input.addEventListener('keydown', keyDown)
input.addEventListener('keypress', keyPress)
input.addEventListener('input', onInput)
input.addEventListener('keyup', keyUp)
input.addEventListener('change', onChange)
input.addEventListener('blur', onBlur)

function onFocus  (event) { info(event) }
function keyDown  (event) { info(event) }
function keyPress (event) {
  info(event)
  // this 2 calls will stop `input` and `change` events
  event.preventDefault();
  event.stopPropagation();
  
  // get current props
  const target = event.target
  const start = target.selectionStart;
  const end = target.selectionEnd;
  const val = target.value;
  
  // get some char based on event
  const char = getChar(event);
  
  // create new value
  const value = val.slice(0, start) + char + val.slice(end);
  
  // first attemp to set value
  // (doesn't work in react because value setter is overrided)
  // target.value = value

  // second attemp to set value, get native setter
  const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
    window.HTMLInputElement.prototype,
    "value"
  ).set;
  nativeInputValueSetter.call(target, value);

  // change cursor position
  target.selectionStart = target.selectionEnd = start + 1;
  
  // dispatch `input` again
  const newEvent = new InputEvent('input', {
    bubbles: true,
    inputType: 'insertText',
    data: char
  })
  event.target.dispatchEvent(newEvent);
}
function keyUp    (event) { info(event) }
function onInput  (event) { info(event) }
function onChange (event) { info(event) }
function onBlur   (event) {
  // dispatch `change` again
  const newEvent = new Event('change', { bubbles: true })
  event.target.dispatchEvent(newEvent);
  info(event)
}

function info     (event) { console.log(event.type) }

function getChar(event) {
  // will show X if letter, will show Y if Digit, otherwise Z
  return event.code.startsWith('Key')
    ? 'X'
    : event.code.startsWith('Digit')
      ? 'Y'
      : 'Z'
}
<input type="text">

答案 5 :(得分:0)

下面是一个简单示例,使用Vanilla JavaScript将_open_osfhandle替换为{ "@timestamp":"2019-06-12T11:11:49.094Z", "@metadata":{ "beat":"filebeat", "type":"doc", "version":"6.2.4" }, "message":"the log line...", "source":"/Users/myusername/tmp/hej.log", "offset":721, "prospector":{ "type":"log" }, "beat":{ "name":"my-macbook.local", "hostname":"my-macbook.local", "version":"6.2.4" } }

,
.