我还没有测试过这段代码(只是把它自由地写进了这个响应中),但这就是我要做的。
在文本输入的 keydown 方法上,您需要监听退格键:
var input = document.getElementById('myInput');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
// Detect Backspace (8) & Delete (46) keys
if( key == 8 || key == 46 ){
var caretPos = getCaretPos(input);
// Read backward from the caret position
// until you hit a space or index 0:
while ( (input.value[caretPos] != " ") && (caretPos > 0) ){
caretPos--;
}
// Once you hit the space or index 0, read forward two characters
// to see if it === "@@". If both chars are "@", cancel
// the keydown event. You should probably do some bounds checking
// here. Could also be done with String.subtring
if ( input.value[(caretPos + 1)] == "@" &&
input.value[(caretPos + 2)] == "@" )
{
return false;
}
}
};
function getCaretPos(input) {
// Internet Explorer Caret Position (TextArea)
if (document.selection && document.selection.createRange) {
var range = document.selection.createRange();
var bookmark = range.getBookmark();
var caret_pos = bookmark.charCodeAt(2) - 2;
} else {
// Firefox Caret Position (TextArea)
if (input.setSelectionRange)
var caret_pos = input.selectionStart;
}
return caret_pos;
}
参考
检测退格
获取插入符号位置
取消keydown事件