浏览器间的差异之 event.keyCode

先看一段示例代码,在不同浏览器中的行为

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script>
$(document).ready(function(){
    $("#test").keydown(function(){
        console.log("jquery_keydown"+event.keyCode);
    }); 
    $("#test").keypress(function(anything){
        console.log("jquery_keypress:"+anything.key);
    });
    $("#test").keyup(function(event){
        console.log("jquery_keyup"+event.keyCode);
    }); 
});
</script>
</head>
<body>
    <button onkeyup="up(event)" onkeydown="down()" onkeypress="press(event)">Test</button>
    <input id="test" type="text">
    <script>
        function up(e){
            console.log("up:"+e.key);
        }
        function down(){
            console.log("down:"+event.key);
        }
        function press(e){
            console.log("press:"+e.keyCode);
        }
    </script>
</body>
</html>

结论

  • “keyup,keydown” returns Character codes (A number which represents an ASCII character)
    “keypress” returns Key codes (A number which represents an actual key on the keyboard

  • To find out if the user is pressing a printable key (e.g. “a” or “5”), it is recommended to use this property on the   onkeypress event. To find out if the user is pressing a function key (e.g. “F1”, “CAPS LOCK” or “Home”) use the onkeydown or onkeyup event.
    功能键建议用 keyup, keydown; 可打印出字的键建议用 keypress

  • In Firefox, the keyCode property does not work on the onkeypress event (will only return 0). For a cross-browser solution, use the which property together with keyCode event.which || event.keyCode
    Firefox下用 keypress 函数 event.keyCode会返回 0 (IE8 以前不支持event.keywhich)

  • Both the keyCode and which property is provided for compatibility only. The latest version of the DOM Events Specification recommend using the key property instead
    最新的DOM Events能用key把字母打出来

  • If you want to find out whether the “ALT”, “CTRL”, “META” or “SHIFT” key was pressed when a key event occured, use the altKey, ctrlKey, metaKey or shiftKey property.
    还有这些关键词可以用如果判断功能键

  • jquery里function第一个参数默认就是 event, 所以给什么变量都行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值