4

我有一个文本框,我想在按退格键或删除键时获取已删除的字符。

我有一个按键事件处理程序,如果按键是退格键,我正在捕获。现在在这里面我需要根据删除的键执行一些任务。请帮忙。

4

3 回答 3

6

在对这个线程getCursorPosition中的函数进行一点调整之后,您可以通过跟踪当前光标选择来删除字符。

该代码处理以下条件:

  1. 键入,然后在末尾退格。
  2. 将光标移动到文本中间并删除/退格。
  3. 选择一段文本,然后删除/退格。
$.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
});

这是现场演示

于 2013-06-09T02:56:47.527 回答
3

您可以改用 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); 
    }
});
于 2013-06-09T02:33:39.977 回答
-1

Live Demo

$('input').keydown(function(e){
    $(this).data('prevVal', $(this).val());   
}).keyup(function(e){
    if(e.keyCode === 8) {//delete
        var ele = $(this); 
        var val = ele.data('prevVal'); 
        var newVal = ele.val(); 
        var removedChar = val.substring(val.length-1);
        alert(removedChar); 
    }
}); 
于 2013-06-09T02:34:51.893 回答