2011-08-27 35 views

回答

4

是的,在飞行中更改它并将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); 
+0

非常感谢,所有的作品都很棒! – JJJollyjim

+0

@ JJ56:干杯,尽管如此,忘记提及(据我所知),这在IE8-上不支持。 – pimvdb

-1

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

$("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}); 
}); 
相关问题