键盘事件keydown、keypress、keyon区别

it2025-04-05  5

键盘事件keydown、keypress、keyon区别

最近刚学习键盘事件,在敲相关案例时,发现有点混淆,思考并查阅资料后发现有些小点很微妙,值得记录以下! 当同时写下这几个事件时,其优先顺序为keydown>keypress>keyup

keyup:当键盘松开时触发;keydown:按下触发;keypress:键盘按下时触发,它并不识别功能键;它虽然很多方面不如keydown,但他可以用来区分字母大小写(即按键的keycode属性)

案例“模拟京东快递单号查询案例” ,如下图效果:

案例分析:

输入内容时,上面盒子(.con)显示字号更大(另外这里用到了css三角形、盒子阴影)。表单检测用户输入:即给表单添加键盘事件(这里使用上述哪个事件值得斟酌,一不小心效果可能不满意哦,后面会详细叙述)。触发事件后会根据下面盒子(.jd)的value给上面盒子(.con)赋值。下面盒子的value值只要为空,则将大号盒子隐藏(display:none),否则,display:block 。

下面贴出详细代码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { margin: 0; padding: 0; } .search { position: relative; width: 178px; margin: 100px; } .con { display: none; position: absolute; top: -40px; width: 171px; border: 1px solid rgba(0, 0, 0, .2); box-shadow: 0 2px 4px rgba(0, 0, 0, .2); padding: 5px 0; font-size: 18px; line-height: 20px; color: #333; } .con::before { content: ''; width: 0; height: 0; position: absolute; top: 28px; left: 18px; border: 8px solid #000; border-style: solid dashed dashed; border-color: #fff transparent transparent; } </style> </head> <body> <div class="search"> <div class="con">123</div> <input type="text" placeholder="请输入您的快递单号" class="jd"> </div> <script> // 快递单号输入内容时, 上面的大号字体盒子(con)显示(这里面的字号更大) // 表单检测用户输入: 给表单添加键盘事件 // 同时把快递单号里面的值(value)获取过来赋值给 con盒子(innerText)做为内容 // 如果快递单号里面内容为空,则隐藏大号字体盒子(con)盒子 var con = document.querySelector('.con'); var jd_input = document.querySelector('.jd'); jd_input.addEventListener('keyup', function() { // console.log('输入内容啦'); if (this.value == '') { con.style.display = 'none'; } else { con.style.display = 'block'; con.innerText = this.value; } }) // 当我们失去焦点,就隐藏这个con盒子 jd_input.addEventListener('blur', function() { con.style.display = 'none'; }) // 当我们获得焦点,就显示这个con盒子 jd_input.addEventListener('focus', function() { if (this.value !== '') { con.style.display = 'block'; } }) </script> </body>

对 点2 进行分析 如果使用keydown或keypress,按键刚按下瞬间,就触发事件,框里文字还未落入,执行if(value==’’),既然value为空,则隐藏大号框,直到再次按下键盘,value不为空,显示上面的框,因此效果如下所示:keypress也更加不会使用,毕竟功能键不识别。

那keyup呢 如果用keyup 按键弹起开始执行 第一个文字已经落入框中 执行else,框显示出来,效果为我们想要的! 另外还想贴出几个鼠标事件 onclick:完成一次完整的鼠标点击过程触发 onmouseover:鼠标经过触发 onmouseout:鼠标离开触发 onfocus:获得鼠标焦点触发 onblur:失去鼠标焦点触发 onmousemove:鼠标移动触发 onmousedown:鼠标按下触发

今天的分享就到这里了~

最新回复(0)