Changing input value while still allowing the user

2020-02-12 12:47发布

问题:

Is it possible, using JavaScript or jQuery, to change the content of a text input field while the user types?

E.g. typing a + up would change the a to å, while keeping the input cursor at the same position.

回答1:

Yes, change it on the fly and keep selectionStart and selectionEnd at the previous position: http://jsfiddle.net/pimvdb/p2jL3/3/.

selectionStart and selectionEnd represent the selection bounds, and are equal to each other when there is no selection, in which case they represent the cursor position.

Edit: Decided to make a jQuery plugin of it, since it may come in handy later and it's easy to implement anywhere that way.

(function($) {
    var down         = {}; // keys that are currently pressed down
        replacements = { // replacement maps
            37: { // left
                'a': 'ã'
            },

            38: { // up
                'a': 'â'
            },

            39: { // right
                'a': 'á'
            },

            40: { // down
                'a': 'à'
            }
        };

    $.fn.specialChars = function() {
        return this.keydown(function(e) {
            down[e.keyCode] = true; // this key is now down

            if(down[37] || down[38] || down[39] || down[40]) { // if an arrow key is down
                var value   = $(this).val(),                         // textbox value
                    pos     = $(this).prop('selectionStart'),        // cursor position
                    char    = value.charAt(pos - 1),                 // old character
                    replace = replacements[e.keyCode][char] || char; // new character if available

                $(this).val(value.substring(0, pos - 1) // set text to: text before character
                            + replace                   // + new character
                            + value.substring(pos))     // + text after cursor

                      .prop({selectionStart: pos,   // reset cursor position
                             selectionEnd:   pos});

                return false; // prevent going to start/end of textbox
            }
        }).keyup(function(e) {
            down[e.keyCode] = false; // this key is now not down anymore
        }).blur(function() {
            down = {}; // all keys are not down in the textbox when it loses focus
        });
    };
})(jQuery);


回答2:

I once had to do a similar thing. I think this is much simpler. Modify it to meet your needs:

$("input#s").keyup(function(e) {
    var m=$("input#s");
    var value= m.val();
    var pos = m.prop('selectionStart');
    value=value.replace(">","»");
    m.val(value);
    m.prop({'selectionStart':pos,'selectionEnd':pos});
});