在文本框上按删除或退格键时删除已删除的字符或文本

See*_*ker 4 javascript events

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

我有一个密钥启动事件处理程序,我正在捕获密钥是否退格.现在在里面我需要根据删除的密钥执行一些任务.请帮忙.

Ari*_*iao 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
});
Run Code Online (Sandbox Code Playgroud)

这是Live Demo