开发者

Custom keyboard / replace keys

开发者 https://www.devze.com 2023-02-20 11:01 出处:网络
I want to chan开发者_运维问答ge behavior of my keyboard so when user on an input box press key a a = 97 it changes to b 97+1.

I want to chan开发者_运维问答ge behavior of my keyboard so when user on an input box press key a a = 97 it changes to b 97+1.

I want it for cross browser


jQuery.keypress will get you the event when the users types something, and String.fromCharCode gets you the character + 1. The tricky part is dealing with the selection.

To get the selection, I used the jQuery field selection plugin, and to make sure it doesn't keep jumping back to the end I used this answer to another question. Here is the final code:

$(function() {
    $("#target").keypress(function (evt) {
        if (evt.which >= 65 && evt.which <= 122) {
            var sel = $(this).getSelection();
            var val = $(this).val();
            var out = val.substring(0, sel.start) + String.fromCharCode(evt.which+1) + val.substring(sel.end, val.length);
            $(this).val(out);
            $(this).selectRange(sel.start + 1, sel.start + 1);
            return false;
        }
    });
});

jsFiddle

I restricted it to a-zA-Z but you can customize that however you want.


I tested the following in Firefox and Chrome. Using "keypress" allows the use of other keys, and using charCode allows using lower and uppercase letters:

document.getElementById("textbox").addEventListener("keypress",function(event){
    event.preventDefault();
    this.value+=(String.fromCharCode(event.charCode+1))
},false);

I just now saw the jQuery tag, so you could also do:

$("#textbox").bind("keypress",function(event){
    event.preventDefault();
    this.value+=(String.fromCharCode(event.charCode+1));
});
0

精彩评论

暂无评论...
验证码 换一张
取 消