如何在没有jQuery或任何其他库的情况下捕获CTRL-S? [英] How do I capture a CTRL-S without jQuery or any other library?

查看:107
本文介绍了如何在没有jQuery或任何其他库的情况下捕获CTRL-S?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在网页中捕获 CTRL + S 事件?

How do I go about capturing the CTRL + S event in a webpage?

我不知道希望使用jQuery或任何其他特殊库。

I do not wish to use jQuery or any other special library.

感谢您的帮助。

推荐答案

如果你只是使用本机/香草JavaScript,这应该达到你所追求的结果:

If you're just using native / vanilla JavaScript, this should achieve the results you are after:

var isCtrl = false;
document.onkeyup=function(e){
    if(e.keyCode == 17) isCtrl=false;
}

document.onkeydown=function(e){
    if(e.keyCode == 17) isCtrl=true;
    if(e.keyCode == 83 && isCtrl == true) {
        //run code for CTRL+S -- ie, save!
        return false;
    }
}

发生了什么事?

onkeydown 方法检查是否按下了CTRL键(键代码 17 )。
如果是这样,我们将 isCtrl 值设置为 true ,以将其标记为已激活并正在使用中。我们可以将此值恢复为 onkeyup 功能中的 false

The onkeydown method checks to see if it is the CTRL key being pressed (key code 17). If so, we set the isCtrl value to true to mark it as being activated and in use. We can revert this value back to false within the onkeyup function.

然后我们会查看是否有其他键与ctrl键一起被按下。在此示例中,密钥代码 83 用于S密钥。您可以在此函数中添加自定义处理/数据操作/保存方法,然后返回 false 以尝试阻止浏览器对CTRL-S键执行操作。

We then look to see if any other keys are being pressed in conjunction with the ctrl key. In this example, key code 83 is for the S key. You can add your custom processing / data manipulation / save methods within this function, and we return false to try to stop the browser from acting on the CTRL-S key presses itself.

这篇关于如何在没有jQuery或任何其他库的情况下捕获CTRL-S?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆