2011-08-27 76 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}); 
}); 
相關問題