在文本框上按Delete或Backspace键可删除字符或文本 [英] Getting deleted character or text on pressing delete or backspace on a textbox
本文介绍了在文本框上按Delete或Backspace键可删除字符或文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本框,我想在按Backspace键或Delete键时获取已删除的字符.
I have a text box, I want to get the deleted character when I press a backspace or delete key.
我有一个按键事件处理程序,并且我正在捕获按键是否为退格键.现在在其中,我需要根据已删除的密钥执行一些任务.请帮忙.
I have a key up event handler and i am capturing if the key is backspace. Now inside this I need to perform some tasks based on the key deleted. Please help.
推荐答案
After making a little tweak for the getCursorPosition
function in this thread, you can get the characters deleted by tracking the current cursor selection.
代码处理以下情况:
- 键入,然后在末尾退格.
- 将光标移到文本的中间并删除/退格.
- 选择一段文本,然后删除/退格.
$.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
});
这是 实时演示
这篇关于在文本框上按Delete或Backspace键可删除字符或文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文