创建一个div,在div上按键盘中的上下左右,这个div会根据你所按的键盘来进行移动,每次移动10px,上哈左右,div会有四个颜色变化,div中的蚊子随着上下左右而变化, 不能穿出图片 超出弹出提示框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>方向键移动div</title>
<style>
#box1 {
width: 200px;
height: 200px;
background-color: aqua;
position: absolute;
}
</style>
<script>
window.onload = function () {
var b1 = document.getElementById("box1");
var distance = 10;
alert("按下ctrl键加速,按下alt键减速");
document.onkeydown = function (event) {
event = event || window.event;
if (event.ctrlKey) {
distance = 40;
}
if (event.shiftKey) {
distance = 5;
}
if (event.keyCode === 37) {
b1.style.left = b1.offsetLeft - distance + "px";
} else if (event.keyCode === 38) {
b1.style.top = b1.offsetTop - distance + "px";
} else if (event.keyCode === 39) {
b1.style.left = b1.offsetLeft + distance + "px";
} else if (event.keyCode === 40) {
b1.style.top = b1.offsetTop + distance + "px";
}
};
};
</script>
</head>
<body>
<div id="box1"></div>
</body>