我有一个文本框,我想在按退格键或删除键时获取已删除的字符.
我有一个密钥启动事件处理程序,我正在捕获密钥是否退格.现在在里面我需要根据删除的密钥执行一些任务.请帮忙.
getCursorPosition在对该线程中的函数进行一些小调整后,可以通过跟踪当前光标选择来删除字符.
该代码处理以下条件:
$.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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11110 次 |
| 最近记录: |