2012-04-12 12 views
0

为了避免在文本区域中键入多个空格,我号召onCLick功能,在KEYUP和下面写禁用文本区域内的多个空间的JavaScript

var val = document.getelemntByID('trmp'); 
val.value = val .value.replace(/ +(?=)/g,''); 

,这是在Firefox中工作正常的代码,在IE7它的工作,但会引起一些其他的问题,比如选择一个单词,并删除它会删除整个文本区域的内容

+0

你就可以生产jsfiddle.net,告诉我们做在浏览器中重现问题是什么? – m90 2012-04-12 09:19:34

+0

http://jsfiddle.net/4G8Lr/14/ - >使用THT编辑IM NT得到正确 – Rosh 2012-04-12 09:26:34

+0

显然你的正则表达式不匹配任何第一次IM:http://jsfiddle.net/4G8Lr/29/尝试任何其他值('/''),它会工作 – m90 2012-04-12 09:37:45

回答

0

我建议不重写所有的时间文本区域的价值,因为它可能存在bug。只是禁止输入空间,如果前一个字符是空间:

$(function(){ 
    var $tA=$('#temp'); 
    $tA.keydown(function(e){ 
     var cursorPos = getCursorPosition($tA.get(0)); 
     if(e.which === 32 && cursorPos > 0 && $tA.val()[cursorPos-1] === ' '){ 
      return false;    
     } 
    }); 
}); 

getCursorPosition = function(el) { 
     var pos = 0; 
     // IE Support 
     if (document.selection) { 
      el.focus(); 
      var Sel = document.selection.createRange(); 
      var SelLength = document.selection.createRange().text.length; 
      Sel.moveStart('character', -el.value.length); 
      pos = Sel.text.length - SelLength; 
     } 
     // Firefox support 
     else if (el.selectionStart || el.selectionStart == '0') 
      pos = el.selectionStart; 

     return pos; 
    } 

http://jsfiddle.net/y6unN/2/