javascript - 我可以得到键码值吗?
问题描述
我可以得到键码值吗?不是代码。
我的意思是当你按下键盘上的“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>
解决方案
从事件中获取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>
推荐阅读
- pandas - 连接分组字符串
- java - spy 对象值不随 when 改变,则返回
- mstest - 任何可用于 specflow 的数据提供者
- javascript - .height 返回的值是实际值的 10 倍以上
- python - 从 Python 列表中获取前 n 个唯一元素
- spring-boot - 尝试获取 Activemq MBean 时出现 InstanceNotFoundException
- javascript - 如何在javascript中动态地将带有数组的深层JS对象减少为没有数组的JS对象?
- javascript - 如何使用 jQuery 控制 CSS 转换的速度?
- json - 如何访问嵌套在牛津词典 API 的多级数组和词典中的定义键?
- python-3.x - 为什么 TensorFlow-gpu 还在使用 cpu