常用键盘事件
键盘事件 | 触发条件 |
---|---|
onkeyup | 某个键盘按键松开时触发 |
onkeydown | 某个键盘按键按下时触发 |
onkeypress | 某个键盘按键被按下时触发,但是它不识别功能键,比如ctrl、方向键等 |
3个事件的执行顺序:
键盘事件对象(e)
对象属性 | 返回 |
---|---|
.key | 按键值 |
.keyCode | 按键值的ascii值 |
注意:
- keyup和keydown事件不区分字母大小写,a和A的keyCode都是65。
- keypress会区分大小写,a是97,A是65。
<!DOCTYPE html>
<html lang="zh">
<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>Document</title>
</head>
<body>
<input type="text">
</body>
<script>
var search = document.querySelector('input');
document.addEventListener('keyup', function(e) {
console.log(e.keyCode);
if (e.keyCode == 83) {
search.focus()
}
})
</script>
</html>
按键获字
<!DOCTYPE html>
<html lang="zh">
<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>Document</title>
</head>
<style>
.search {
width: 15%;
position: relative;
margin-top: 10%;
}
input {
width: 100%;
}
.con {
display: none;
width: 100%;
height: 128%;
box-shadow: 0 2px 4px rgb(0 0 0 / 20%);
padding: 1px 3px;
line-height: 184%;
position: absolute;
top: -165%;
}
.con::before {
content: "";
width: 0;
height: 0;
border: 6px solid;
border-color: white transparent transparent;
position: absolute;
top: 100%;
left: 20%;
}
</style>
<body>
<div class="search">
<div class="con"></div>
<input type="text" placeholder="请输入您的快递单号">
</div>
</body>
<script>
var con = document.querySelector('.con');
var input = document.querySelector('input');
input.addEventListener('keyup', function() {
if (this.value == '') {
con.style.display = 'none';
con.innerHTML = ''
} else {
con.style.display = 'block'
con.innerHTML = this.value
}
})
input.addEventListener('blur', function() {
con.style.display = 'none'
})
input.addEventListener('focus', function() {
con.style.display = 'block'
})
document.addEventListener('keyup', function(e) {
// console.log(e.keyCode);
if (e.keyCode == 83) {
input.focus()
}
})
</script>
</html>
- 快递单号输入内容时,上面的大号盒子(con)显示这里的文字
- 同时把快递单号里面的值(value)获取过来赋值给con盒子(innerText)做为内容
- 如果快递单号里面内容为空,则隐藏大号字体盒子(con)盒子
- keydown和keypress在文本框里面的特点:他们两个事件触发的时候,文字还没有写入文本框中。
- keyup事件触发的时候,文字已写入文本框