首页 > 解决方案 > 我可以得到键码值吗?

问题描述

我可以得到键码值吗?不是代码。
我的意思是当你按下键盘上的“D”键时它会返回 68,它可以返回“D”吗?我没有换档键或制表键。
有可能吗?

(function(){
let this_, keycode_;

$('textarea')
.on('keydown', function(e){
  this_ = e.target;
  keycode_  = e.keyCode || e.which;
})
.on('input', function(){
  $('#log').text( keycode_ ); 
})
.on('keyup', function(){

});

})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
i want to get keycode_ value, not the code.
i mean when you push "D" key on keyboard it will return 68, can it return "D" ? and i got nothing for shift key or tab. 
can you solve this? 
-->
<textarea></textarea>

<div id="log"></div>

标签: javascriptjquery

解决方案


从事件中获取key属性而不是keyCode属性:

(function() {
  let this_, keycode_;

  $('textarea')
    .on('keydown', function(e) {
      this_ = e.target;
      keycode_ = e.keyCode == 9 ? 'Tab' : (e.shiftKey ? 'Shift' : (e.key || e.which));
      $(this).trigger('input');
    })
    .on('input', function() {
      $('#log').text(keycode_);
    })
    .on('keyup', function() {

    });

})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
i want to get keycode_ value, not the code.
i mean when you push "D" key on keyboard it will return 68, can it return "D" ? and i got nothing for shift key or tab. 
can you solve this? 
-->
<textarea></textarea>

<div id="log"></div>


作为替代方案,您还可以使用String.fromCharCode()将键码转换为字符:

(function() {
  let this_, keycode_;

  $('textarea')
    .on('keydown', function(e) {
      this_ = e.target;
      keycode_ = String.fromCharCode(e.keyCode || e.which);
    })
    .on('input', function() {
      $('#log').text(keycode_);
    })
    .on('keyup', function() {

    });

})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--
i want to get keycode_ value, not the code.
i mean when you push "D" key on keyboard it will return 68, can it return "D" ? and i got nothing for shift key or tab. 
can you solve this? 
-->
<textarea></textarea>

<div id="log"></div>


推荐阅读