且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在文本框上按Delete或Backspace键可删除字符或文本

更新时间:2023-12-02 22:39:10

After making a little tweak for the getCursorPosition function in this thread, you can get the characters deleted by tracking the current cursor selection.

代码处理以下情况:

  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
});

这是 实时演示