Javascript Ctrl+;防止在Chrome中出现默认值

Javascript Ctrl+;防止在Chrome中出现默认值,javascript,jquery,google-chrome,preventdefault,Javascript,Jquery,Google Chrome,Preventdefault,我想在Chrome中捕获Ctrl+S,并阻止默认浏览器行为来保存页面。怎么做 (我在这之后很长一段时间都没有找到解决方案,只是发布了问题和答案)据我所知,秘密在于,Ctrl+S不会触发按键事件,只有按键事件 使用: 仅适用于jQuery: $(document).bind('keydown', function(e) { if(e.ctrlKey && (e.which == 83)) { e.preventDefault(); alert('Ctrl+S')

我想在Chrome中捕获Ctrl+S,并阻止默认浏览器行为来保存页面。怎么做


(我在这之后很长一段时间都没有找到解决方案,只是发布了问题和答案)

据我所知,秘密在于,Ctrl+S不会触发按键事件,只有按键事件

使用:

仅适用于jQuery:

$(document).bind('keydown', function(e) {
  if(e.ctrlKey && (e.which == 83)) {
    e.preventDefault();
    alert('Ctrl+S');
    return false;
  }
});
编辑2012.12.17-jQuery.hotkeys

如果您位于输入元素内部,则不会跟踪热键(除非您 直接将热键显式绑定到输入)。这有助于避免 与正常用户键入冲突

“借”自

document.onkeydown=函数(e){
e=e | | window.event;//获取事件
如果(e.ctrlKey){
var c=e.which | | e.keyCode;//获取密钥代码
开关(c){
案例83://块Ctrl+S
e、 预防默认值();
e、 停止传播();
打破
}
}
};

一体式解决方案,防止数据丢失

// disable right click
$(function() {
    $(this).bind("contextmenu", function(e) {
        e.preventDefault();
    });
}); 

// Prevent F12      
$(document).keydown(function (event) {
    if (event.keyCode == 123) { // Prevent F12
        return false;
    } else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) { // Prevent Ctrl+Shift+I        
        return false;
    }
});

//stop copy of content
function killCopy(e){
    return false
}
function reEnable(){
    return true
}
document.onselectstart=new Function ("return false")
    if (window.sidebar){
    document.onmousedown=killCopy
    document.onclick=reEnable
}

// prevent ctrl + s
$(document).bind('keydown', function(e) {
  if(e.ctrlKey && (e.which == 83)) {
    e.preventDefault();
    return false;
  }
});

当文本区域或输入字段被聚焦时,jQuery.hotkeys的可能重复项似乎无法捕获事件。@BrianM.Hunt非常正确,谢谢。引用文档,因为这是一个文档化的“功能”提示:不要使用
keyup
,这将始终首先触发保存对话框。始终使用
按键
@KaiNoack非常感谢!我一直很困惑,为什么我的代码不起作用,但没有人指出这一关键事实!提示:不要使用jQuery,这只会带来悲伤。注意,在2k21不推荐使用的情况下,现在使用的是
keyboardEvent.key=='s'
。。。事实上,当我可以编辑>:D时,为什么要发表评论
document.addEventListener("keydown", function(e) {
  if (e.key === 's' && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
    e.preventDefault();
    alert('captured');
  }
}, false);
// disable right click
$(function() {
    $(this).bind("contextmenu", function(e) {
        e.preventDefault();
    });
}); 

// Prevent F12      
$(document).keydown(function (event) {
    if (event.keyCode == 123) { // Prevent F12
        return false;
    } else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) { // Prevent Ctrl+Shift+I        
        return false;
    }
});

//stop copy of content
function killCopy(e){
    return false
}
function reEnable(){
    return true
}
document.onselectstart=new Function ("return false")
    if (window.sidebar){
    document.onmousedown=killCopy
    document.onclick=reEnable
}

// prevent ctrl + s
$(document).bind('keydown', function(e) {
  if(e.ctrlKey && (e.which == 83)) {
    e.preventDefault();
    return false;
  }
});