gpt4 book ai didi

Javascript 键码冲突 : "right arrow" and "single quote"

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:04:23 25 4
gpt4 key购买 nike

下面的脚本做了它应该做的事情,也就是说,它对“左箭头”和“右箭头”键使用react。但是,由于键码冲突,它也会对单引号使用react。这使得无法将该字符输入到输入字段中。对此有什么办法吗?

<script type="text/javascript">
onload = function(){
document.onkeypress=function(e){
if(window.event) e=window.event;
var keycode=(e.keyCode)?e.keyCode:e.which;

switch(keycode){
case 37: window.location.href='set.jsp?index=5';
break;
case 39: window.location.href='set.jsp?index=7';
break;
}
}
}
</script>

最佳答案

当用户按下单引号键时,e.keyCode属性为0,e.which属性为39。执行String.fromCharCode (39) 返回单引号。

如果该属性在事件对象中,您需要 keyCode:

var keycode = "keyCode" in e ? e.keyCode : e.which;

这样,当该属性存在于事件对象中并且 which 属性也存在时,您的 keyCode 将为零。

document.onkeydown = function(event) {
event = event || window.event;

var keyCode = "keyCode" in event ? event.keyCode : event.which;

switch (keyCode) {
case 37: console.log("37 was pressed", event); break;
case 39: console.log("39 was pressed", event); break;
}
};

编辑 #1:其他评论者和答案是正确的。我忘了你不应该用 keypress 事件检测控制键。更改为 onkeydown

跨浏览器的完整 HTML 示例:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Key Codes Test</title>
</head>
<body>
<script type="text/javascript">
document.onkeydown = function(event) {
event = event || window.event;

var keyCode = "keyCode" in event ? event.keyCode : event.which;

switch (keyCode) {
case 37: console.log("37 was pressed", event); break;
case 39: console.log("39 was pressed", event); break;
}
};
</script>
<input type="text" size="30">
</body>
</html>

关于Javascript 键码冲突 : "right arrow" and "single quote",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27861696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com