javascript 按文本框上的删除或退格键获取已删除的字符或文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17005823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting deleted character or text on pressing delete or backspace on a textbox
提问by Seeker
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.
我有一个按键事件处理程序,我正在捕获按键是否为退格键。现在在这里面我需要根据删除的键执行一些任务。请帮忙。
回答by Arie Xiao
After making a little tweak for the getCursorPosition
function in this thread, you can get the characters deleted by tracking the current cursor selection.
对该线程中的getCursorPosition
功能进行一些调整后,您可以通过跟踪当前光标选择来删除字符。
The code handles the following conditions:
该代码处理以下条件:
- Type and then backspace at the end.
- Move cursor in the middle of the text and delete/backspace.
- Select a piece of text and then delete/backspace.
- 键入,然后在最后退格。
- 将光标移动到文本中间并删除/退格。
- 选择一段文本,然后删除/退格。
$.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
});
And here is Live Demo
这是现场演示
回答by Herman Tran
You could use the keydown event handler instead so that the last character to be deleted is still available:
您可以改用 keydown 事件处理程序,以便最后一个要删除的字符仍然可用:
$('textarea').on('keydown',function(e) {
var deleteKeyCode = 8,
value = $(this).val(),
length = value.length,
lastChar = value.substring(length-1, length);
if (e.which === deleteKeyCode) {
alert(lastChar);
}
});