我有一个文本框,我想在按退格键或删除键时获取删除的字符。
我有一个按键事件处理程序,如果按键是退格键,我将捕获。现在,在其中我需要根据已删除的密钥执行一些任务。请帮忙。
做了一些调整后getCursorPosition
函数于这个线程 https://stackoverflow.com/questions/1891444/how-can-i-get-cursor-position-in-a-textarea,您可以通过跟踪当前光标选择来删除字符。
该代码处理以下条件:
- 键入,然后在末尾退格。
- 将光标移动到文本中间并删除/退格。
- 选择一段文本,然后删除/退格。
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
var posEnd = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
posEnd = el.selectionEnd;
} else if('selection' in document) {
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;
posEnd = Sel.text.length;
}
// return both selection start and end;
return [pos, posEnd];
};
$('#text').keydown(function (e) {
var position = $(this).getCursorPosition();
var deleted = '';
var val = $(this).val();
if (e.which == 8) {
if (position[0] == position[1]) {
if (position[0] == 0)
deleted = '';
else
deleted = val.substr(position[0] - 1, 1);
}
else {
deleted = val.substring(position[0], position[1]);
}
}
else if (e.which == 46) {
var val = $(this).val();
if (position[0] == position[1]) {
if (position[0] === val.length)
deleted = '';
else
deleted = val.substr(position[0], 1);
}
else {
deleted = val.substring(position[0], position[1]);
}
}
// Now you can test the deleted character(s) here
});
这是现场演示 http://jsfiddle.net/ArieShout/c5daT/2/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)