如何更改Firefox中键入的字符 [英] How to change characters typed in Firefox

查看:104
本文介绍了如何更改Firefox中键入的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在输入文本时将字符。更改为,。
在IE中我更改了keypress事件中的keyCode事件属性,比如这个

I need to change in a text input the character '.' to ',' while typing. In IE I change the keyCode event property in the keypress event, like this

document.getElementById('mytext').onkeypress = 
 function (evt) {
  var e = evt || window.event;
  if (e.keyCode && e.keyCode==46)
   e.keyCode = 44;
  else if (e.which && e.which==46) {
   e.which = 44;
  }
 };

但它似乎在Firefox中无法更改键事件中输入的字符。
有什么建议吗?

but it seemes that in Firefox it's impossible to change characters typed in key events. Any suggestions?

推荐答案

试试这个。它适用于所有浏览器:

Try this. It works on all browsers:

window.onload = function () {
    var input = document.getElementById("mytext");

    input.onkeypress = function () {
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is it a period?
        if (char == ".") {
            // Replace it with a comma
            input.value += ",";

            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};

更新: Pier Luigi 指出了以上问题。它没有照顾插入位置不在文本的末尾。即使你在文本中插入了一些文本,它也会将命令附加到结尾。

Update: Pier Luigi pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value.

解决方法是模拟按键,而不是附加逗号逗号键的事件。不幸的是,在不同的浏览器中调度合成事件的方式似乎表现出很多种类,并不是一件容易的事。我会看看能否为它找到一个不错的通用方法。

The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.

这篇关于如何更改Firefox中键入的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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