gpt4 book ai didi

Javascript 计数器在按键输入而不是按钮上?

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:41 24 4
gpt4 key购买 nike

所以我有这个计数器可以增加“正”和“负”值,它工作正常。现在我还想指定键盘键来增加值,“f”表示负值,“j”表示正值。我该怎么做呢?我一直在摆弄 onkeypress/onkeyup 但它仍然令人困惑。

<html>
<head>
<script type="text/javascript">

function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty,10) + val;

if (new_qty < 0) {
new_qty = 0;
}

document.getElementById('qty').value = new_qty;
return new_qty;
}

function modify_qtyn(val) {
var qtyn = document.getElementById('qtyn').value;
var new_qtyn = parseInt(qtyn,10) + val;

if (new_qtyn < 0) {
new_qtyn = 0;
}

document.getElementById('qtyn').value = new_qtyn;
return new_qtyn;
}

</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div class="box">
<label for="Positive"><abbr title="Positive">Qty</abbr></label>
<label for="Negative"><abbr title="Negative">Qtyn</abbr></label>
<input id="qtyn" value="0" />
<input id="qty" value="0" />
<button id="down" onclick="modify_qtyn(1)">MINUS</button>
<button id="up" onclick="modify_qty(1)">PLUS</button>


</div>

</body>
</html>

我通过添加以下内容找到了解决方案:

function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
if (key==102) {modify_qtyn(1);}
if (key==70) {modify_qtyn(1);}
if (key==106) {modify_qty(1);}
if (key==74) {modify_qty(1);}
};
};

最佳答案

您可以使用事件keypress在标签 <body>甚至在 window 。检查这个event的文档.

<body onkeypress="func(event)">

window.addEventListener('keypress', func);

请参阅此func您阅读了event.key作为第一个参数传递以验证是字母“f”还是“j”。

关于Javascript 计数器在按键输入而不是按钮上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44998750/

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