为了避免在文本区域中输入多个空格,我正在调用一个函数 on onCLick
, on keyup 并编写下面的代码
var val = document.getelemntByID('trmp');
val.value = val .value.replace(/ +(?= )/g,'');
这在 Firefox 中运行良好,在 IE7 中运行良好,但会导致一些其他问题,例如选择一个单词并删除它会删除整个文本区域内容
为了避免在文本区域中输入多个空格,我正在调用一个函数 on onCLick
, on keyup 并编写下面的代码
var val = document.getelemntByID('trmp');
val.value = val .value.replace(/ +(?= )/g,'');
这在 Firefox 中运行良好,在 IE7 中运行良好,但会导致一些其他问题,例如选择一个单词并删除它会删除整个文本区域内容
我建议不要一直重写 textarea 的值,因为它可能是错误的。如果前一个字符是空格,只需禁用输入空间:
$(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;
}
仅将正则表达式用于空格。添加键码条件。