在jQuery中绑定ctrl + u键击

时间:2012-11-15 09:00:33

标签: javascript jquery onkeyup

我正在尝试在 jQuery 中将热键构建到我的Web应用程序中。我试图绑定 Ctrl + U 键击。这就是我所拥有的:

$(document).keypress(function(e) {
    if(e.ctrlKey && e.which == 117) {
      if($("#nav-user-details").length > 0) {
        $("#nav-user-details").find(".dropdown-menu").toggle();
      }
    }
});

这不行。如何绑定这些击键?

感谢。

6 个答案:

答案 0 :(得分:3)

请试试 http://jsfiddle.net/TN7GZ/

Ctrl + U ,屏幕将发出警告。

这符合您的需求:)

<强>代码

var isCtrl = false;
document.onkeyup=function(e){
    if(e.which == 17) isCtrl=false;
}
document.onkeydown=function(e){
    if(e.which == 17) isCtrl=true;
    if(e.which == 85 && isCtrl == true) {
        //run code for CTRL+U -- ie, whatever!
        alert('CTRL + U stuff');
        return false;
    }
}
​

答案 1 :(得分:1)

我很确定85u的关键代码,或者我错过了什么?

如果你也想要mac支持(命令键),它可能会变得混乱。我之前写了一个片段可能对你有帮助,但它涉及浏览器检测(哎呀):

var cmd = false;

$(document).on('keydown', function(e) {

    if(detectMacCommand(e.which)) {
        cmd = true;
        return;
    }

    // now detect print (ctr/cmd + p)
    if ( e.which == 85 && ( e.ctrl || cmd ) ) {
        e.preventDefault();
        alert('ctrl/cmd + u');
    }

}).on('keyup', function(e) {

    if(detectMacCommand(e.which)) {
        cmd = false;
        return;
    }

});

function detectMacCommand(key) {
    return ( $.browser.mozilla && key == 224 ||
             $.browser.opera   && key == 17 ||
             $.browser.webkit  && ( key == 91 || key == 93 ));
}

演示:http://jsbin.com/afijam/2

答案 2 :(得分:0)

你必须使用keydown而不是keypress。 Keypress不会触发非char键。

$(document).keydown(function (e) {
  if (e.ctrlKey && e.which === 81) {
    alert("key pressed");
    return false;
  }
});

答案 3 :(得分:0)

$(document).keypress("u",function(e) {
  if(e.ctrlKey)
    alert("Ctrl+U was pressed!!");
});

答案 4 :(得分:0)

试试这个:

var prevKey = null;
$(document).keydown(function (e) {
  var thisKey = e.which;

  if (prevKey && prevKey == 17) {
    if (thisKey == 85) {
      // Your code.
    }
  }

  prevKey = thisKey;
});

答案 5 :(得分:0)

如果您使用Xhtml文件但收到错误The entity must immediately follow the &,则应使用&&amp;&amp;代替&&

相关问题