event.which
针对键盘和鼠标事件,这个属性能确定你到底按的是哪个键。
event.which
event.which将event.keyCode和event.charCode标准化了。推荐用event.which来监视键盘输入。
event.which也将正常化的按钮按下(mousedown和mouseupevents),左键报告1,中间键报告2,右键报告3。使用event.which代替event.button。
例子
记录按键
<!DOCTYPE html>
<html>
<head>
<script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
</head>
<body>
<input id="whichkey" value="" placeholder="input" />
<div id="log"></div>
<script>$('#whichkey').on('keydown',function (e){
$('#log').html(e.type + ': ' + e.which );
}); </script>
</body>
</html>
记录按下的鼠标按钮
<!DOCTYPE html>
<html>
<head>
<script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
</head>
<body>
<input id="whichkey" value="" placeholder="input" />
<div id="log"></div>
<script>
$('#whichkey').on('mousedown',function (e){
$('#log').html(e.type + ': ' + e.which );
});
</script>
</body>
</html>
