jQuery鍵盤事件,繫結事件與移除事件,複合事件
鍵盤事件是指每次按下或者釋放鍵盤上得按鍵時所產生的事件,常用的鍵盤事件的方法:
keydown() :按下鍵盤時觸發的事件方法;
keyup() :釋放按鍵時觸發的事件方法;
keypress() :產生可列印的字元時觸發的事件方法;
<!DOCTYPE html>
<html lang="zh">
<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>
<script src="js/jquery-3.2.1.js"></script>
<script type="text/javascript">
$(document).keydown(function(event){
//按下回車鍵時觸發,keyCode為13時,表示回車鍵
if(event.keyCode=="13"){
alert("你按下了回車鍵");
}
});
</script>
</head>
<body>
</body>
</html>
未按下回車鍵時:
按下回車鍵時:
繫結事件:
1.繫結一個事件:jQuery物件.blind(type,[data],fn);
2.繫結多個事件:jQuery物件.blind(type:fn,type:fn,...,type:fn);
type: 事件型別,如click , focus , mouseover等
data: 可選引數,可以作為event.data的屬性值,傳遞給事件物件額外的資料;
fn: 處理函式,用來繫結該事件的處理函式。
繫結單個事件:
<!DOCTYPE html>
<html lang="zh">
<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>
<script src="js/jquery-3.2.1.js"></script>
<script>
$(document).ready(function(){
$("#dog").bind("click",function(){
$(this).css("background-color","yellow");
});
});
</script>
</head>
<body>
<div id="dog" style="border: 1px solid blue;">我們時英雄</div>
</body>
</html>
未點選<div>時:
點選<div>後:
繫結多個事件:
<!DOCTYPE html>
<html lang="zh">
<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>
<script src="js/jquery-3.2.1.js"></script>
<script>
$(document).ready(function(){
$("#myDog").bind({
mouseover:function(){
$(this).css("background-color","yellow");
},
mouseout:function(){
$(this).css("background-color","blue");
}
});
});
</script>
</head>
<body>
<div id="myDog">wo are hero</div>
</body>
</html>
滑鼠未移動到<div>時:
滑鼠移動到<div>時:
滑鼠離開<div>時:
移除事件:
jQuery物件。unbind([type],[fn])
type: 事件型別,如click,focus,mouseover等
fn: 處理函式,用於解除繫結的事件函式。
當unbind()不帶引數時,表示移除繫結的全部事件。
複合事件:
jQuery物件.hover(fn1,fn2)
其中,fn1相當於mouseover(),fn2相當與mouseout()。
<!DOCTYPE html>
<html lang="zh">
<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>
<script src="js/jquery-3.2.1.js"></script>
<script>
$(document).ready(function(){
$("#myDog").hover(
function(){
$(this).css("background-color","greenyellow");
},
function(){
$(this).css("background-color","blue");
}
);
});
</script>
</head>
<body>
<div id="myDog">wo are hero</div>
</body>
</html>
滑鼠未移動到<div>時:
滑鼠移動到<div>時:
滑鼠離開到<div>時: