【问题标题】:Changing input value while still allowing the user to type更改输入值,同时仍允许用户键入
【发布时间】:2011-08-27 20:33:14
【问题描述】:

是否可以使用 JavaScript 或 jQuery 在用户键入时更改文本输入字段的内容?

例如键入a + up 会将a 更改为å,同时将输入光标保持在同一位置。

【问题讨论】:

    标签: javascript jquery html input


    【解决方案1】:

    是的,即时更改它并将selectionStartselectionEnd 保留在之前的位置:http://jsfiddle.net/pimvdb/p2jL3/3/

    selectionStartselectionEnd 表示选择范围,在没有选择时相等,此时它们代表光标位置。

    编辑:决定用它做一个jQuery插件,因为它以后可能会派上用场,而且很容易在任何地方实现。

    (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);
    

    【讨论】:

    • @JJ56: 干杯,忘记提了(据我所知)IE8 不支持这个。
    【解决方案2】:

    我曾经不得不做类似的事情。我认为这要简单得多。修改它以满足您的需求:

    $("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});
    });
    

    【讨论】:

      猜你喜欢
      • 2014-10-26
      • 1970-01-01
      • 2017-02-08
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2011-07-27
      相关资源
      最近更新 更多