How to have a page support to typing keyboard to launch a modal?

十年热恋 提交于 2019-12-13 09:07:31

问题


This link would launch a jupyter notebook.

When the page is loaded,

typing h, would launch a modal ("Keyboard shortcuts")

typing f, would launch another modal "Find and Replace"

How to have a page support to typing keyboard to launch a modal?

This link gives some inspiration inside modal.

This and this give examples about a single element, although I am asking an approach to listen keypress event on whole page

question

Here is my code which is trying to listen any keypress

<!DOCTYPE html>
<html>

<head>
    <script>
        i = 0;
        $(document).querySelector('#myDiv').addEventListener('keyup', function (e) {
            $("span").text(i += 1);
        })
    </script>
</head>

<body>
    <div class="container" id="mydiv" tabindex="0">
        <p>Keypresses: <span>0</span></p>
    </div>

</body>

</html>

How to make this code work?


回答1:


You are wiring the event incorrectly. With jQuery, use on() to wire the event and provide the selector for your target element in the second argument:

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    i = 0;
    $(document).on('keyup', '#mydiv', function(e) {
      $("span").text(i += 1);
    })
  </script>
</head>

<body>
  <div class="container" id="mydiv" tabindex="0">
    <p>Keypresses: <span>0</span></p>
  </div>
</body>

Of course, remember to click inside the element before you start typing. Now, if you want to know what key was pressed, you can use e.key. That's good if you want to get the characters, but if you want to implement shortcuts, it's better to use e.keyCode:

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    $(document).on('keyup', '#mydiv', function(e) {
      $("span").text(e.key + " (" + e.keyCode + ")");
    })
  </script>
</head>

<body>
  <div class="container" id="mydiv" tabindex="0">
    <p>Keypresses: <span>0</span></p>
  </div>
</body>



回答2:


maybe you should try this

    document.addEventListener('keyup', function (event) {
            if (event.defaultPrevented) {
                return;
            }

            var key = event.key || event.keyCode;
            console.log(key); // which "key" is the key you clicked on
            // Then you should test which key is clicked so you can do whatever you want like so
            if(key == 'Esc'){
              //Do the magic

            }
        });


来源:https://stackoverflow.com/questions/58022233/how-to-have-a-page-support-to-typing-keyboard-to-launch-a-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!