键盘事件
//键盘操作
//1.某键盘按下执行的操作 document是对文档进行触发
document.onkeyup = function(){
console.log('你好')
}
document.addEventListener('keyup',function(){
console.log('你好')
})
//2.某键盘按下操作,此执行,只要键盘一直按着,就一直重复执行
document.onkeydown = function(){
console.log('按了键盘')
}
document.addEventListener('keydown',function(){
console.log('我按下了键盘')
})
document.addEventListener('keypress',function(){ //keypress 事件是不能识别功能键的,比如:ctrl、左右箭头
console.log('我按了press键')
})
//注意:如果keyup、keydown和keypress,同时出现执行顺序 keydown->keypress->keyup
//可以查看到执行过程和属性
document.addEventListener('keyup',function(e){
console.log(e)
})
//keyCode 是对应键盘的Ascll码值
//注意:keyup和keydown 不区分字母大小写,如果想区分可以用可以keypress
案例一:
//京东首页按s键光标自动定位到搜索框
var search = document.querySelector('input');
document.addEventListener('keyup',function(){ //用keyup事件是因为keydown执行并将内容赋值给input.value
if(e.keyCode === 83) { //s的Ascll码是83
search.focus(); //让搜索框得到光标
}
})
案例二:
//京东订单查询功能
<!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" class="jd" placeholder="请输入快递单号">
</div>
<script>
思路:
// 快递单号输入内容时, 上面的大号字体盒子(con)显示(这里面的字号更大)
// 表单检测用户输入: 给表单添加键盘事件
// 同时把快递单号里面的值(value)获取过来赋值给 con盒子(innerText)做为内容
// 如果快递单号里面内容为空,则隐藏大号字体盒子(con)盒子
//获取元素
var con = document.querySelector('.con');
var jd_input = document.querySelector('.jd');
jd_input.addEventListener('keyup',function(){
/*注意:事件触发keydown和keypress在文本框里面的特点:
他们两个事件触发的时候,文字还没有落入文本中去*/
if (this.value == ''){
con.style.display = 'none';
} else {
con.style.display = 'block';
con.innerHTML = this.value;
}
})
//得到焦点
jd_input.addEventListener('blur',function(){
con.style.display = 'none';
})
//失去焦点
jd_input.addEventListener('foucs',function(){
if(jd_input !== ''){
con.style.display = 'block'
}
})
</script>
</body>
</html>