更改按键

发布于 2024-10-10 15:03:30 字数 619 浏览 12 评论 0原文

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

我并不关心在 IE 中工作的解决方案 - 只是在 Safari、Chrome 和 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、which 和 keyCode 之外,还有一个“originalEvent”属性,该属性又具有这些属性。但是,我无法修改这些(我尝试使用 e.originalEvent.charCode = 102 之类的东西)。

In an input box or contenteditable=true div, how can I modify a keypress for the letter "a" to return a keybress for the letter "b"? I.e., every time you type the letter "a" in the div, the output is actually the letter "b".

I'm not that concerned with a solution that works in IE--just one that works in Safari, Chrome, & FF.

In Chrome, I can see that a keypress event has the properties "charCode", "keyCode", and "which", all of which get assigned the keypress event number. If I fire an event on a keypress, I can modify these values, but I can't figure out what to return so that the actual key that gets typed is different. For example:

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

I can also see that along with charCode, which, and keyCode, there is also an "originalEvent" property which in turn also has these properties. However, I haven't been able to modify those (I tried with things like e.originalEvent.charCode = 102).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

谢绝鈎搭 2024-10-17 15:03:31

我不确定这是否“容易”做到,就像这样:

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

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

I'm not sure if this is "easily" do-able, with something like this:

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

I do know that jQuery has a simulate plug-in to simulate keypress events etc, jQuery Simulate. It might be worth looking into - also possibly some type of jQuery Trigger() event.

花间憩 2024-10-17 15:03:31

我也遇到了这个问题。最后我通过以下代码解决了这个问题:

$('.my_input_box').keyup(function(){
    //my execution code is here
});

它已经过测试。它在我的项目中发挥了作用。

I was also faced this problem. and Finally I solved it by following code:

$('.my_input_box').keyup(function(){
    //my execution code is here
});

It's tested. It has worked in my project.

ら栖息 2024-10-17 15:03:30

您无法更改与按键事件关联的字符或按键,也无法完全模拟按键事件。但是,您可以自己处理按键并在当前插入点/插入符处手动插入所需的字符。我在 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/

You can't change the character or key associated with a key event, or fully simulate a key event. However, you can handle the keypress yourself and manually insert the character you want at the current insertion point/caret. I've provided code to do this in a number of places on Stack Overflow. For a contenteditable element:

Here's a jsFiddle example: http://www.jsfiddle.net/Ukkmu/4/

For an input:

Cross-browser jsFiddle example: http://www.jsfiddle.net/EXH2k/6/

IE >= 9 and non-IE jsFiddle example: http://www.jsfiddle.net/EXH2k/7/

云胡 2024-10-17 15:03:30

这是一个使用 Vanilla JavaScript 将 , 替换为 . 的简单示例

// change ',' to '.'
document.getElementById('only_float').addEventListener('keypress', function(e){
    if (e.key === ','){
        // get old value
        var start = e.target.selectionStart;
        var end = e.target.selectionEnd;
        var oldValue = e.target.value;

        // replace point and change input value
        var newValue = oldValue.slice(0, start) + '.' + oldValue.slice(end)
        e.target.value = newValue;

        // replace cursor
        e.target.selectionStart = e.target.selectionEnd = start + 1;

        e.preventDefault();
    }
})
<input type="text" id="only_float" />

Here a simple example to replace , to . using Vanilla JavaScript

// change ',' to '.'
document.getElementById('only_float').addEventListener('keypress', function(e){
    if (e.key === ','){
        // get old value
        var start = e.target.selectionStart;
        var end = e.target.selectionEnd;
        var oldValue = e.target.value;

        // replace point and change input value
        var newValue = oldValue.slice(0, start) + '.' + oldValue.slice(end)
        e.target.value = newValue;

        // replace cursor
        e.target.selectionStart = e.target.selectionEnd = start + 1;

        e.preventDefault();
    }
})
<input type="text" id="only_float" />

小巷里的女流氓 2024-10-17 15:03:30

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

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

My solution example (change in input[type=text] the character ',' to '.'):

element.addEventListener('keydown', function (event) {
if(event.key === ','){
  setTimeout(function() {
    event.target.value += '.';
  }, 4);
  event.preventDefault();
};
满天都是小星星 2024-10-17 15:03:30

,您可以对

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

那么 方法可能无法处理所有可能的技巧,你可以用真正替换“按下”字符的东西来实现,但我不知道有什么方法可以真正做到这一点。

编辑 - 哦,我在超时处理程序中输入“修复”的示例的原因是,它确保浏览器有机会处理“按键”的本机行为“ 事件。当超时处理程序代码运行时,我们确信元素的值将被更新。我意识到这段代码有点货物崇拜的味道。

Well what you could do for an <input> or <textarea> is just make sure that the value doesn't have any "a" characters in it:

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

This approach probably couldn't handle all the possible tricks you could pull with something that really swapped out the "pressed" character, but I don't know any way to actually do that.

edit — oh, and the reason that I typed in that example with the "fixup" happening in a timeout handler is that it makes sure that the browser has the opportunity to handle the native behavior for the "keypress" event. When the timeout handler code runs, we're sure that the value of the element will have been updated. There's a touch of the cargo cult to this code, I realize.

零時差 2024-10-17 15:03:30

这是一个不使用任何库的示例

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">

Here is an example without using any libraries

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">

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文