【问题标题】:How to fire an event in jquery when alt+tab or windows+d is pressed?按下alt + tab或windows + d时如何在jquery中触发事件?
【发布时间】:2013-12-03 05:07:22
【问题描述】:

我想在按下 alt+tab 或 windows+d 时触发一个事件。以下是我在鼠标指针远离浏览器窗口时发出警报的代码。但即使用户按下 alt+tab 或 Windows+D 也应该发生此事件。任何人都可以在这方面帮助我吗?以下是我的代码供您参考:

<!DOCTYPE html>
<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
    <script>
      var timer;
      $(document).ready(function () {
        $(document).mouseleave(function () {
          //alert("Mouse is away");
          customAlert("your mouse is away");
        });
      });

      function customAlert(customText) {
        $("#popUp").html(customText);
        timer = setInterval(customAlert2, 5000);

        $("#popUp").dialog({
          dialogClass: "no-close",
          buttons: [{
                      text: "OK", click: function () {
                        $(this).dialog("close");
                        clearInterval(timer);
                      }
                    }]
        });
      }

      function customAlert2() {
        location.reload();
        $("#popUp2").dialog({
        dialogClass: "no-close",
        buttons: [{
                  text: "OK", click: function () {
                    $(this).dialog("close");
                  }
                }]
        });
      }


    </script>
  </head>
  <body>
    <h1>My first Javascript program</h1>
    <p>Hello World!</p>
    <div id="popUp" title="First alert message"></div>
    <div id="popUp2" title="Second alert message">Time is over</div>
  </body>
</html>

【问题讨论】:

  • JavaScript 只能“看到”浏览器中发生的事情。
  • @PHPLover,你找到答案了吗?
  • 我想你可以对 HTML5 Visibility API 感兴趣 davidwalsh.name/page-visibility

标签: javascript jquery


【解决方案1】:

注意,如果您想处理他们通过操作系统注册的任何键(例如:Alt+Tab)您CAN不 Jquery 这样做。

您需要将您的事件分配给未注册的键以使用 Jquery 触发您的事件。

你可以尝试一些代码,比如 blow 来处理你想要的东西

var keys = {};

 $(document).keydown(function (e) {
  keys[e.which] = true;
 });

 $(document).keyup(function (e) {
   delete keys[e.which];
});

if( (keys[91] && keys[68]) || (keys[18] && keys[9]) ) /*windows+d OR alt+tab*/
{ /* your code */}


或者

使用jwerty lib 来做。示例代码:

jwerty.key('ctrl+shift+P', function () { 
   // your code
});

并支持组合:

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { 
   // your code
});


还有一个简单的 javaScript 库Mousetrap 用于处理键盘快捷键。看一下这个例子:
Mousetrap.bind('h', function() {
    // your code
});

还支持组合:

Mousetrap.bind(['ctrl+h', 'ctrl+l'], function(e) {
    // your code
}

希望对你有用。

【讨论】:

    【解决方案2】:

    jwerty 是一个很棒的插件,它允许您为特定的组合键创建功能。

    例如:

    jwerty.key('ctrl+shift+P', function () { [...] });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-11
      • 2011-10-20
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      相关资源
      最近更新 更多