我正在根据 keydown
、keypress
和 keyup
事件操作 3 个表格单元格的背景颜色。
html
<table border="1px">
<tr><th>Event</th><th>Action</th><th>Value</th></tr>
<tr><td>Keydown</td><td id="down"></td><td id="downvalue"></td></tr>
<tr><td>Keypress</td><td id="press"></td><td id="pressvalue"></td></tr>
<tr><td>Keyup</td><td id="up"></td><td id="upvalue"></td></tr>
</table>
<input type="text" id="txt" /><br />
JS
window.onload = function()
{
document.getElementById("txt").addEventListener("Keydown", keyisdown(), false);
document.getElementById("txt").addEventListener("Keyup", keyisup(), false);
document.getElementById("txt").addEventListener("Keypress", keyispress(), false);
}
function keyisdown()
{
document.getElementById("press").style.backgroundColor = "white";
document.getElementById("up").style.backgroundColor = "white";
document.getElementById("down").style.backgroundColor = "red";
}
// above function is repeated twice for keyisup and keyispress
我应该在字段中输入内容,并分别更改背景颜色,但所有这些都在页面加载或刷新时运行一次,然后再也不会运行,我该如何解决?谢谢。
最佳答案
第一个错误是您在 window.load
上执行函数。仅将函数名称传递给 eventListener,删除函数名称后的 ()
。
第二:使用 .onkeydown
而不是附加事件监听器。
第三:我希望您不要试图在按向上箭头键和向下箭头键时更改单元格的颜色。 onkeydown
和 onkeyup
函数不会记录按下的是哪个键。你必须为此使用 .keyCode
。
在下面的示例中,我只包含了 .onkeydown
函数,它在按下 arrowkeyup 时将 down 的颜色更改为绿色,在按下 arrowkeydown 时更改为红色。
window.onload = function()
{
document.getElementById("txt").onkeydown = function(e){
document.getElementById("press").style.backgroundColor = "white";
document.getElementById("up").style.backgroundColor = "white";
var code = e.keyCode;
if(code==40){
document.getElementById("down").style.backgroundColor = "red";
}
else if(code==38){
document.getElementById("down").style.backgroundColor = "green";
}
}
}
<table border="1px">
<tr><th>Event</th><th>Action</th><th>Value</th></tr>
<tr><td>Keydown</td><td id="down"></td><td id="downvalue"></td></tr>
<tr><td>Keypress</td><td id="press"></td><td id="pressvalue"></td></tr>
<tr><td>Keyup</td><td id="up"></td><td id="upvalue"></td></tr>
</table>
<input type="text" id="txt"/><br />
关于javascript - 函数执行一次且 addEventlistener 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41519790/