2012-03-21 30 views

回答

1

例如使用jQuery:

$("#landing-search-input").keyup(function(event) { 
    if (event.keyCode == 188) { 
     $(this).val($(this).val() + " "); 
    } 
}); 

$("#landing-search-input").keyup(function(event) { 
    var inputValue = $(this).val(); 
    if (inputValue.substr(-1) == ",") { 
     $(this).val(inputValue + " "); 
    } 
}); 
+0

當插入符號不在輸入文本的末尾時,這將不起作用。 – 2012-03-21 09:24:20

1

如果你想這樣做正確,這樣

  1. 的空間在正確的位置添加當插入符號不在輸入文本的末尾
  2. 插入符號是plac編輯立即正確插入

後面的空格之後......你需要像下面這樣,這將在所有主要的瀏覽器,包括IE 6

演示:http://jsfiddle.net/Y9c6G/

代碼:

function insertTextAtCursor(el, text) { 
    var val = el.value, endIndex, range; 
    if (typeof el.selectionStart != "undefined" 
      && typeof el.selectionEnd != "undefined") { 
     endIndex = el.selectionEnd; 
     el.value = val.slice(0, endIndex) + text + val.slice(endIndex); 
     el.selectionStart = el.selectionEnd = endIndex + text.length; 
    } else if (typeof document.selection != "undefined" 
      && typeof document.selection.createRange != "undefined") { 
     el.focus(); 
     range = document.selection.createRange(); 
     range.collapse(false); 
     range.text = text; 
     range.select(); 
    } 
} 

document.getElementById("some_input").onkeypress = function(evt) { 
    evt = evt || window.event; 
    var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode; 
    if (String.fromCharCode(charCode) == ",") { 
     insertTextAtCursor(this, ", "); 
     return false; 
    } 
}; 
相關問題