<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0%;
padding: 0%;
}
#box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
}
</style>
<script>
window.onload = function () {
/*----------使div可以根据不同的方向键向不同的方向移动----------*/
//定义一个变量来表示速度
var spead = 20;
//创建一个变量来表示方向
//通过修改dir来影响移动的方向
var dir ;
//开启一个定时器,来控制div的移动
setInterval(function () {
switch (dir) {
case 37:
box1.style.left = box1.offsetLeft - spead + "px";
break;
case 38:
box1.style.top = box1.offsetTop - spead + "px";
break;
case 39:
box1.style.left = box1.offsetLeft + spead + "px";
break;
case 40:
box1.style.top = box1.offsetTop + spead + "px";
break;
case 87:
box1.style.top = box1.offsetTop - spead + "px";
break;
case 83:
box1.style.top = box1.offsetTop + spead + "px";
break;
case 65:
box1.style.left = box1.offsetLeft - spead + "px";
break;
case 68:
box1.style.left = box1.offsetLeft + spead + "px";
break;
}
},30);
//获取box1
var box1 = document.getElementById("box1");
//为document绑定一个键盘事件
document.onkeydown = function (event) {
event = event || window.event;
//当用户按了shift键之后速度加快
if (event.shiftKey) {
spead = 100;
}
else{
spead = 20;
}
dir = event.keyCode;
}
//当按键松开时,div不在移动
document.onkeyup = function(){
//设置方向为零
dir = 0;
};
};
</script>
</head>
<body>
<div id="box1"></div>
</body>
</html>
修改div移动练习
最新推荐文章于 2022-07-24 21:04:53 发布