jQuery 事件 - keydown() 方法的应用
实现一个需求:当按住键盘的上下左右键的时候,自定义一个小球会向你控制的方向移动。
原理:当发生 keydown 事件时运行一个函数,结合上下左右四个键位的ASCII 码实现不同的效果。
效果展示:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<style>
.div1{
width: 100px;
height:100px;
position: absolute;
left:50%;
margin-left:-50px;
background: #af1819;
border-radius: 50%;
}
</style>
<body>
<div class="div1"></div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script>
$(document).keydown(function(e){
if(e.keyCode==40) //向下移动
{
$(".div1").css("top",parseInt($('.div1').css('top'))+10+'px') //parseInt()字符串转换成数字
};
if(e.keyCode==38)
{
console.log(parseInt($('.div1').css('top')) -10 +'px');
$(".div1").css("top",parseInt($('.div1').css('top')) -10 +'px')
};
if(e.keyCode==37)
{
// console.log(e.keyCode)
$(".div1").css("left",parseInt($('.div1').css('left'))-10+'px')
};
if(e.keyCode==39)
{
// console.log(e.keyCode)
$(".div1").css("left",parseInt($('.div1').css('left'))+10+'px')
};
})
</script>
</html>