Using JavaScript to simulate JD.COM key input function

  • 2021-10-11 17:31:34
  • OfStack

When I saw this function, I was also surprised that JD.COM actually made such a function. In the website version of JD.COM Mall, no matter where you are, just press the S key to locate the cursor to the search bar for search. Although this is a very good function, it seems that few people know it.

The program implementation is very simple, in the s key rise when the search box can get the focus.


<!DOCTYPE html>
<html lang="zh-CN">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title> Press S Key cursor positioning search box </title>
</head>
<body>
 <input type="text">
 <script>
  var search = document.querySelector('input');
  document.addEventListener('keyup',function(e){
   // You can use the console.log(e.keyCode) Print 1 Under S Key ASCII Value 
   if(e.keyCode === 83){
    search.focus();
   }
  })
  // Used here keyup Without using keydown , 
  //keydown Triggered when the keyboard is pressed, the focus is placed in the search box, and then it is triggered S Key, make S Enter the search box. 
  // And use keyup Is to get the focus when the keyboard returns, so it will not appear in the search box s.
 </script>
</body>
</html>

Attached: Keyboard Events keydown () and keyup ()

1. Keyboard press event: keydown () is triggered when the keyboard is pressed

2. Keyboard pop-up event: keyup () is triggered when the keyboard is released


  <h1>keydown() And keyup() Events </h1>
  <div style="margin:10px 0 20px 20px;">
    <input class="keydown k1" type="text" placeholder=" Eavesdropping keydown Input :" />
     Press to display the entered value :<em style="font-weight: 900;color: red;"></em>
  </div>
  <div style="margin:20px 0 0 20px;">
    <input class="keyup k1" type="text" placeholder=" Eavesdropping keyup Input :" />
     Release the display of the entered value :<em style="font-weight: 900;color: red;"></em>  
  </div>
  <script src="~/Content/jquery.2.1.4.min.js"></script>
  <script>
    $(".keydown").keydown(function (e) {
      $("em").first().text(e.target.value);
    });
    $(".keyup").keyup(function (e) {
      $("em:last").text(e.target.value);
    });
  </script>

Executing the above code block shows that

keydown event triggers the text before entering the text box. If the text in the text box is output in keydown event, the text before triggering the keyboard event is obtained, while the operation of the whole keyboard event is completed when keyup event triggers, and the text after triggering the keyboard event is obtained

Summarize


Related articles: