最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how detect CTRL+q in javascript - Stack Overflow

programmeradmin0浏览0评论

How detect ctrl+q with javascript, this is my code

<body>
    <p id="x"></p>
    <script>
       window.onkeydown = function() {detect(event);}
       window.onkeypress = function() {res(event);}
       var act = false;
       function detect(event) {
           if(event.ctrlKey) {
              act = true;
           }
           else
               act = false;
       }
        function res(event) {
            if(act) {
                document.getElementById("x").innerHTML = "ctrl " + String.fromCharCode(event.which);
            }
            else
                document.getElementById("x").innerHTML = String.fromCharCode(event.which);
        }
    </script>
</body>

I want do it with javascript only.

How detect ctrl+q with javascript, this is my code

<body>
    <p id="x"></p>
    <script>
       window.onkeydown = function() {detect(event);}
       window.onkeypress = function() {res(event);}
       var act = false;
       function detect(event) {
           if(event.ctrlKey) {
              act = true;
           }
           else
               act = false;
       }
        function res(event) {
            if(act) {
                document.getElementById("x").innerHTML = "ctrl " + String.fromCharCode(event.which);
            }
            else
                document.getElementById("x").innerHTML = String.fromCharCode(event.which);
        }
    </script>
</body>

I want do it with javascript only.

Share Improve this question edited May 29, 2016 at 13:02 dbf 3,4631 gold badge26 silver badges34 bronze badges asked May 29, 2016 at 12:51 EhsanEhsan 13k3 gold badges26 silver badges46 bronze badges 2
  • 4 This question was already asked: see how-to-find-out-what-character-key-is-pressed – wake-0 Commented May 29, 2016 at 12:55
  • @KevinWallis So we flag it :) – dbf Commented May 29, 2016 at 13:03
Add a ment  | 

1 Answer 1

Reset to default 10

You can detect it using the following function:

document.addEventListener("keydown", function (event) {
  event.stopPropagation();
  event.preventDefault();

  if(event.ctrlKey && event.keyCode == 81)
  {
    console.log("CTRL + Q was pressed!");
  }
  else
  {
    console.log("Something else was pressed.");
  }
});

The stopPropagation() and preventDefault() calls prevent the browser's default behaviour from occurring.

If you want to detect other keys, this page is rather useful: http://asquare/javascript/tests/KeyCode.html

发布评论

评论列表(0)

  1. 暂无评论