开发者

How intercept these two key: ":" and "."?

I need to do something when a user presses . and something else when an user presses :.

Is there a way to intercept these two keys with 开发者_如何学GoJavaScript, jQuery or other?


Assuming you want to intercept these keys on the whole document:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
    if (charCode) {
        var charStr = String.fromCharCode(charCode);
        if (charStr == ":") {
            alert("Colon!");
        } else if (charStr == ".") {
            alert("Full stop!");
        }
    }
};

Marcel Korpel rightly points out in the comments that it's more efficient not to use the String.fromCharCode() call; here's a version without:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = (typeof evt.which == "undefined") ? evt.keyCode : evt.which;
    if (charCode) {
        if (charCode == 58) {
            alert("Colon!");
        } else if (charCode == 46) {
            alert("Full stop!");
        }
    }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜