解决:无法引发Form.KeyUp或Form.KeyDown事件

本文介绍了在包含TextBox的窗体中使用KeyUp或KeyDown事件时遇到的问题及解决方案。通过设置this.KeyPreview=true,窗体可以接收KeyPress、KeyDown和KeyUp事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果我们的窗体内有至少一个TextBox,那么,在注册From的KeyUp或KeyDown事件后会发现,这个事件无法引发。

解决方法是添加 this.KeyPreview = true;

关于KeyPreview属性,MSDN解释如下:

“当此属性设置为 true 时,窗体将接收所有 KeyPress、KeyDown 和 KeyUp 事件。在窗体的事件处理程序处理完该击键后,然后将该击键分配给具有焦点的控件。例如,如果 KeyPreview 属性设置为 true,而且当前选定的控件是 TextBox,则在窗体的事件处理程序处理了击键后,TextBox 控件将接收所按的键。”

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JS-事件-常见事件</title> </head> <body> <form action="" style="text-align: center;"> <input type="text" name="username" id="username"> <input type="text" name="age" id="age"> <input id="b1" type="submit" value="提交"> <input id="b2" type="button" value="单击事件"> </form> <br><br><br> <table width="800px" border="1" cellspacing="0" align="center"> <tr> <th>学号</th> <th>姓名</th> <th>分数</th> <th>评语</th> </tr> <tr align="center"> <td>001</td> <td>张三</td> <td>90</td> <td>很优秀</td> </tr> <tr align="center" id="last"> <td>002</td> <td>李四</td> <td>92</td> <td>优秀</td> </tr> </table> <script> //click: 鼠标点击事件 document.querySelector('#b2').addEventListener('click', () => { console.log("我被点击了..."); }) //mouseenter: 鼠标移入 document.querySelector('#last').addEventListener('mouseenter', () => { console.log("鼠标移入了..."); }) //mouseleave: 鼠标移出 document.querySelector('#last').addEventListener('mouseleave', () => { console.log("鼠标移出了..."); }) //keydown: 某个键盘的键被按下 document.querySelector('#username').addEventListener('keydown', () => { console.log("键盘被按下了..."); }) //keydown: 某个键盘的键被抬起 document.querySelector('#username').addEventListener('keyup', () => { console.log("键盘被抬起了..."); }) //blur: 失去焦点事件 document.querySelector('#age').addEventListener('blur', () => { console.log("失去焦点..."); }) //focus: 元素获得焦点 document.querySelector('#age').addEventListener('focus', () => { console.log("获得焦点..."); }) //input: 用户输入时触发 document.querySelector('#age').addEventListener('input', () => { console.log("用户输入时触发..."); }) //submit: 提交表单事件 document.querySelector('form').addEventListener('submit', () => { alert("表单被提交了..."); }) </script> </body> </html>为什么submit不使用#b1,而是使用form
最新发布
07-31
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值