JS设置div根据键盘移动

使用js设置div根据方向键“上、下、左、右”方向键移动,

代码如下:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>键盘移动</title>
 <script src="https://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
	.s-move-content-outer{border:1px black solid;width:200px;height:200px;position:relative;outline:none;user-select:none;/*overflow:hidden;*/;}
    .s-move-content-header{background-color:pink;width:100%;height:30px;text-align:center;line-height:30px;}
</style>
</head>
 
<body>
	<div class="s-move-content-outer" tabIndex="1" >
		<div class="s-move-content-header" tabIndex="1" >div1 </div>
		<div>内容1</div>
	</div>
</body>
</html>
 
<script>
//键盘控制移动
$(document).keydown(function(event){
    var keyNum = event.which;   //获取键值
    var Item = $(".s-move-content-outer");   //要移动的元素
    switch(keyNum){  //判断按键
		case 37: Item.animate({left:'-=5px'});break;
		case 38: Item.animate({top:'-=5px'});break;
		case 39: Item.animate({left:'+=5px'});break;
		case 40: Item.animate({top:'+=5px'});break;
		default:
        break;
    
    }
});
</script>

猜你喜欢

转载自blog.csdn.net/yuyecsdn/article/details/89636584