<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../jquery-1.12.1.js"></script>
<script>
$(function () {
$("#txt").focus(function () {
console.log("焦点已经获取");
$("#sp").text("焦点已经获取");
});
$("#btn").click(function () {
$("#txt").triggerHandler("focus");
});
});
</script>
</head>
<body>
<input type="button" value="获取焦点" id="btn"/>
<input type="text" value="" id="txt"/>
<span id="sp"></span>
</body>
</html>
事件参数对象
$(function () {
$("#dv").mousedown(function (e) {
console.log(e);
});
});
案例获取用户按下键盘的键值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script src="../jquery-1.12.1.js"></script>
<script>
$(function () {
$("#dv").mousedown(function (e) {
if(e.altKey){
console.log("用户按下了alt键和鼠标");
}else if(e.shiftKey){
console.log("用户按下了shift键和鼠标");
}else if(e.ctrlKey){
console.log("用户按下了ctrl键和鼠标");
}else {
console.log("用户只按下了鼠标");
}
});
});
</script>
</head>
<body>
<div id="dv"></div>
</body>
</html>
案例按键改变背景颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div {
width: 800px;
height: 600px;
background-color: forestgreen;
}
</style>
<script src="../jquery-1.12.1.js"></script>
<script>
$(function () {
$(document).keydown(function (e) {
switch (e.keyCode) {
case 65:
$("#dv").css("backgroundColor", "red");
break;
case 66:
$("#dv").css("backgroundColor", "blue");
break;
case 67:
$("#dv").css("backgroundColor", "yellow");
break;
case 68:
$("#dv").css("backgroundColor", "pink");
break;
case 69:
$("#dv").css("backgroundColor", "black");
break;
}
});
});
</script>
</head>
<body>
<div id="dv"></div>
</body>
</html>