如何截取这两个键:“:”和“。”?

发布于 2024-09-24 00:15:51 字数 112 浏览 0 评论 0原文

当用户按 . 时,我需要执行某些操作,当用户按 : 时,我需要执行其他操作。

有没有办法用 JavaScript、jQuery 或其他方法拦截这两个键?

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 JavaScript, jQuery or other?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够钟 2024-10-01 00:15:51

假设您想在整个文档中拦截这些键:

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 在注释中正确地指出,不使用 String.fromCharCode() 调用会更有效;这是一个没有以下版本的版本:

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

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!");
        }
    }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文