Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

javascript - Getting Deleted character

in in Input field, if the user presses Backspace or Delete key, is there a way to get the deleted character.

I need to check it against a RegExp.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following will work in all major browsers for text <input> elements. It shouldn't be used for <textarea> elements because the getInputSelection function doesn't account for line breaks correctly in IE. See this answer for a (longer) function that will do this.

function getInputSelection(input) {
    var start = 0, end = 0;
    input.focus();
    if (    typeof input.selectionStart == "number" &&
            typeof input.selectionEnd == "number") {

        start = input.selectionStart;
        end = input.selectionEnd;
    } else if (document.selection && document.selection.createRange) {
        var range = document.selection.createRange();
        if (range) {
            var inputRange = input.createTextRange();
            var workingRange = inputRange.duplicate();
            var bookmark = range.getBookmark();
            inputRange.moveToBookmark(bookmark);
            workingRange.setEndPoint("EndToEnd", inputRange);
            end = workingRange.text.length;
            workingRange.setEndPoint("EndToStart", inputRange);
            start = workingRange.text.length;
        }
    }
    return {
        start: start,
        end: end,
        length: end - start
    };
}

document.getElementById("aTextBox").onkeydown = function(evt) {
    evt = evt || window.event;
    var keyCode = evt.keyCode;
    var deleteKey = (keyCode == 46), backspaceKey = (keyCode == 8);
    var sel, deletedText, val;
    if (deleteKey || backspaceKey) {
        val = this.value;
        sel = getInputSelection(this);
        if (sel.length) {
            deletedText = val.slice(sel.start, sel.end);
        } else {
            deletedText = val.charAt(deleteKey ? sel.start : sel.start - 1);
        }
        alert("About to be deleted: " + deletedText);
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...