您可以使用此代码:
$('.singleSpace').keyup(function() {
var foo = $(this).val().replace(/^( *)([^ ] *)(.*)/g, function(_,b,c,d){
return $.trim(c) + ' ' + d.replace(/ /g, '').slice(0,40);
})
$(this).val(foo)
});
唯一的问题是光标位置。如果在光标不在末尾时键入,光标将始终返回末尾。
自己看看:http://jsfiddle.net/S3gJL/2/
我建议你把这个函数放在一个模糊事件中,但这也很烦人。
您的要求一点也不简单。有很多变化,用户可以复制粘贴,选择和删除。万事难防。
上面提供的代码阻止了很多弯路(唯一没有阻止的是右键粘贴可能还有其他我没有想到的东西),但说明了成本更多。您可能想搜索插件或聘请某人开发一个好的系统。
编辑 1
删除第一个之后写空间的授权。
编辑 2
对于此处的光标位置进行修复:
$('.singleSpace').keyup(function() {
var foo = this.value.replace(/^( *)([^ ] *)(.*)/g, function(a,b,c,d,e){
return $.trim(c) + ' ' + d.replace(/ /g, '').slice(0,40);
})
var carretPos = doGetCaretPosition(this)
carretPos += foo.length - this.value.length
this.value = foo;
setSelectionRange(this, carretPos, carretPos)
});
//Code taken from
// http://stackoverflow.com/questions/17858174/set-cursor-to-specific-position-on-specific-line-in-a-textarea
function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
//Code taken from
// http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field
function doGetCaretPosition (oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange ();
// Move selection start to 0 position
oSel.moveStart ('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}
FIDDLE